Photon Server初识(六) --- 客户端与服务端消息传递
前一章客户端与服务端连接成功,现在需要前后端进行数据传递。
一、前端发送消息。在项目Scripts目录中新建脚本 TestSer.cs。并挂载到相机上
二、客户端发送数据给服务端。编辑客户端代码 TestSer.cs。让鼠标点击时发送消息
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestSer : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { //如果鼠标点击了 if (Input.GetMouseButtonDown(0)) { SendRequest(); } } void SendRequest() { Debug.Log("点击了------"); //包装需要发送的数据 Dictionary<byte, object> data = new Dictionary<byte, object>(); data.Add(1, 120); data.Add(2, "clent to ser"); //向服务端发送数据,发送code是1,服务端需要用到 PhotonManager.Peer.OpCustom(1, data, true); } }
三、服务端接收数据,并返回数据给客户端。编辑服务端代码 ClientPeer.cs。
using System.Collections.Generic; using Photon.SocketServer; using PhotonHostRuntimeInterfaces; namespace MyGameServer { public class ClientPeer : Photon.SocketServer.ClientPeer { //创建客户端 public ClientPeer(InitRequest initRequest) : base(initRequest) { } protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters) { MyGameServer.log.Info("Client---请求了---" + operationRequest.OperationCode); //通过opCode区分 switch (operationRequest.OperationCode) { //客户端测试数据发送的code是1,所以在1里面接收数据 case 1: //接收客户端传来的数据 Dictionary<byte, object> data = operationRequest.Parameters; object intValue; data.TryGetValue(1, out intValue); object strValue; data.TryGetValue(2, out strValue); MyGameServer.log.Info("Client---客户端传的数据--" + intValue.ToString() + "---" + strValue.ToString()); //服务端返回数据给前端 //包装数据,发送代码为 1,前端取数据需要用到 OperationResponse opResult = new OperationResponse(1); Dictionary<byte, object> datav2 = new Dictionary<byte, object>(); datav2.Add(1, 120); datav2.Add(2, "server to Client"); opResult.SetParameters(datav2); MyGameServer.log.Info("Client---返回数据给客户端了---"); SendOperationResponse(opResult, sendParameters); //发送数据给前端 break; case 2: break; default: break; } } //处理客户端断开连接 protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail) { MyGameServer.log.Info("Client------断开了"); } } }