上次把服务器端的代码稍微写了一下,能够正常通信,并没有去做客户端。今天把客户端的代码稍微写了一下,包括协议的发送接收。
SuperSocket提供了接收客户端协议的一个类,我们只需进行重写一下,就可以接收来自客户端的数据了。
SuperSocket协议类的代码
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
namespace WpfSuperSocket.SuperSocket
{
public class TestCommand1 : CommandBase
{
public override void ExecuteCommand(SHZSession session, StringRequestInfo requestInfo)
{
MainWindow.instance.Dispatcher.Invoke((Action)delegate ()
{
//显示在UI面板上
MainWindow.instance.InfoLbl.Content += "\r\n" + requestInfo.Body + "\r\n";
string TestJson = "{\"action\":10001,\"serverId\":1,\"playerId\":1001,\"address\":{\"street\":\"HongQiao road.\",\"city\":\"Changning, Shanghai\",\"country\":\"China\"},\"links\":[{\"name\":\"Shihuangzhe\",\"url\":\"http://www.shihuangzhe.org\"},{\"name\":\"Shihuangzhe\",\"url\":\"http://www.shihuangzhe.org\"}]}";
//向客户端发送数据
session.Send(TestJson);
});
}
}
}
用于和服务器通信
using LitJson;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class DMNetControl : MonoBehaviour
{
public delegate void RespondOfHttpJD(JsonData jsonStr);
public delegate void RespondOfHttpDic(Dictionary jsonDic);
public static DMNetControl Instance;
private Socket ClinetSocket;
private const string Ip = "127.0.0.1";
private const int Prot = 2017;
void Awake()
{
Instance = this;
ClinetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse(Ip);
IPEndPoint point = new IPEndPoint(ipAddress, Prot);
ClinetSocket.Connect(point);
}
#region Socket通信代码
///
/// 向服务器发送消息,并接收来自服务器的回复消息
///
/// 发送给服务器的字节
/// 服务器返回给客户端的回调数据
void ReceiveMessage(byte[] _strBytes, RespondOfHttpJD _respondFunction)
{
try
{
this.ClinetSocket.Send(_strBytes);
if (_respondFunction != null)
{
_respondFunction(AsynRecive(ClinetSocket));
}
}
catch (Exception ex)
{
Debug.LogError("写Error日志"+ex.ToString());
}
}
///
/// Socket 消息回传
///
///
public JsonData AsynRecive(Socket socket)
{
try
{
byte[] msg = new byte[1024];
var da = Encoding.UTF8.GetString(msg);
int recv=socket.Receive(msg);
//因为SuperSocket发送的数据带有\r\n换行符,所以在接收到数据的时候要进行特殊处理,
//要把‘\r\n’去掉,否则json转换会出错
string str = Encoding.UTF8.GetString(msg, 0, recv).Replace("\r\n", " ");
JsonData jd = JsonMapper.ToObject(str);
return jd;
}
catch (Exception ex)
{
socket.Close();
return "Socket 消息回传,写Error日志" + ex.Message;
}
}
///
/// 发送给服务器的数据
///
/// 服务器端,协议类名
/// 发送给服务器的json数据
/// 服务器返回给客户端的数据
public void RequestOfSocket(string _scriptName, DMNetForm _netForm, RespondOfHttpJD respondFunction)
{
string jdStr = JsonMapper.ToJson(_netForm.GetSendObj);
string jd = _scriptName + jdStr + "\r\n";
Debug.LogError(jd);
byte[] strBytes = Encoding.UTF8.GetBytes(jd);
ReceiveMessage(strBytes, respondFunction);
}
#endregion
}
向服务器发送的json数据存储
using System.Collections.Generic;
public class DMNetForm
{
public DMNetForm()
{
}
public DMNetForm(int pact)
{
fromdic.Add("action" ,pact);
}
Dictionaryfromdic=new Dictionary();
public Dictionary GetSendObj { get {return fromdic;} }
public void addField(string _key, object _value, int data = 0)
{
if (fromdic.ContainsKey(_key))
{
fromdic[_key] = _value;
return;
}
fromdic.Add(_key,_value);
}
}
客户端协议脚本
using LitJson;
using UnityEngine;
using UnityEngine.UI;
public class Client : MonoBehaviour
{
public Text text;
public InputField input;
private DMNetForm netForm;
public void Send()
{
//向服务器发送数据的格式。
//服务器端,协议类名
string scriptName = "TestCommand1 ";
//协议号(和服务器约定好的)
netForm=new DMNetForm(10001);
//下面是给向服务器发送的数据
netForm.addField("serverId",1);
netForm.addField("playerId", 1001);
//发送的json格式:TestCommand1 {"action":10001,"serverId":1,"playerId":1001}
//====================================================================
//接收来自于服务器回复的消息
//接收的json格式:
/*
{
"action": 10001,
"serverId": 1,
"playerId": 1001,
"address": {
"street": "Science Park Road.",
"city": "Suzhou, Jiangsu",
"country": "China"
},
"links": [
{
"name": "Shihuangzhe",
"url": "http://www.shihuangzhe.org"
},
{
"name": "Shihuangzhe",
"url": "http://www.shihuangzhe.org"
}
]
}
*/
DMNetControl.Instance.RequestOfSocket(scriptName,netForm, delegate (JsonData jd) {
Debug.Log(jd["action"].ValueAsInt());
Debug.Log(jd["serverId"].ValueAsInt());
for (int i = 0; i {
Debug.Log(jd["address"][i].ValueAsString());
}
for (int i = 0; i {
Debug.Log(jd["links"][i]["name"].ValueAsString());
}
});
}
}
Demo下载
链接:http://pan.baidu.com/s/1o7KnnvG 密码:y325
最后编辑:2017-03-30作者:shengruqing
这个作者貌似有点懒,什么都没有留下。
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!