设计为四个部分,第一部分接收发送数据,第二部分本地数据转换为字节发送到服务器包括发送包长度,包头,加密,具体内容等.第三部分接收byte转换为数据.第四部分监听.
第一部分简单示例:连接服务器Ip 端口,发送请求,接收数据同理.
- public static void SocketConnect(string serverIP, int serverPort)
- {
- clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
- try
- {
- clientSocket.Connect(ipe);
- Debug.Log(" Connect Success IP: " + serverIP + " Port : " + serverPort.ToString());
- }
- catch (Exception e)
- {
- Debug.LogError(e.ToString());
- }
- }
- //发送数据
- public static void Send(byte[] bytes)
- {
- if (clientSocket == null)
- return;
- if (!clientSocket.Connected)
- return;
- if (clientSocket.Poll(0, SelectMode.SelectWrite))
- {
- try
- {
- clientSocket.Send(bytes);
- }
- catch (Exception e)
- {
- Debug.LogError(e.ToString());
- }
- }
- }
- public void _MSG_ACCOUNT(string name, string pwd)
- {
- ACCOUNT account = new ACCOUNT();
- datas = new byte[account.length];
- byte[] bytesLength = BitConverter.GetBytes((System.Int16)account.length);
- int length = 0;
- bytesLength.CopyTo(datas, length);
- length += 2;
- byte[] bytesID = BitConverter.GetBytes((System.Int16)account.ID);
- bytesID.CopyTo(datas, length);
- length += 2;
- byte[] bytesName = Encoding.Default.GetBytes(name);
- bytesName.CopyTo(datas, length);
- void _MSG_CONNECT(byte[] datas)
- {
- connect = new CONNECT();
- int length = 4;
- connect.idAccount = BitConverter.ToUInt32(datas, length);
- Debug.LogError("账号ID " + connect.idAccount);
- length += System.Runtime.InteropServices.Marshal.SizeOf(connect.idAccount);
- connect.dwData = BitConverter.ToUInt32(datas, length);
- Debug.LogError("认证ID " + connect.dwData);
- length += System.Runtime.InteropServices.Marshal.SizeOf(connect.dwData);
- connect.nServerIndex = BitConverter.ToUInt32(datas, length);
- Debug.LogError("游戏逻辑服务器索引 " + connect.nServerIndex);