继搭建好简单的服务端后,开始尝试进行客户端的连接,交互
客户端代码
public class PhotonEngineTest : MonoBehaviour, IPhotonPeerListener
{
private static PhotonEngineTest Instance;
private static PhotonPeer peer;
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(this.gameObject);
}
else if (Instance != this)
{
Destroy(this.gameObject);
return;
}
}
// Use this for initialization
void Start()
{
if (peer==null)
{
Debug.Log(peer);
peer = new PhotonPeer(this, ConnectionProtocol.Udp);
}
peer.Connect("127.0.0.1:5055", "GameServer");
Debug.Log(peer);
}
// Update is called once per frame
void Update()
{
peer.Service();
}
public static PhotonPeer Peer
{
get { return peer; }
}
public void DebugReturn(DebugLevel level, string message)
{
}
//接受服务端返回的消息
public void OnOperationResponse(OperationResponse operationResponse)
{
switch (operationResponse.OperationCode)
{
case 1:
Debug.Log("case 1 ,Server's Response");
object intvalue;
object strvalue;
Dictionary<byte, object> date = operationResponse.Parameters;
date.TryGetValue(1, out intvalue);
date.TryGetValue(2, out strvalue);
Debug.Log("the response data is "+intvalue+" and "+strvalue);
break;
case 2:
Debug.Log("case 2 ,Server's Response");
break;
}
}
public void OnStatusChanged(StatusCode statusCode)
{
Debug.Log(statusCode);
}
public void OnEvent(EventData eventData)
{
}
public void OnDestory()
{
if (peer != null & peer.PeerState == PeerStateValue.Connected)
{
peer.Disconnect();
// peer.StopThread();
}
}
}
class Test:MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
SendMessage();
}
}
//向服务端发起请求
void SendMessage()
{
Dictionary<byte, object> data = new Dictionary<byte, Object>();
data.Add(1, 5);
data.Add(2,"chenyongchao");
//通过建立的连接发送数据
PhotonEngineTest.Peer.OpCustom(1,data, true);
}
}
服务端代码