unity-code-异步客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using Newtonsoft.Json;
using UnityEngine;
using System.Collections.Generic ;

public class AA
{
public int m_int;
public float m_float;
public string m_string;
public List<int> m_list = new List<int>();
public string[] m_arr = new string[3];
}

public class SocketListener : MonoBehaviour
{
//public delegate void HandleAction(int msgType, string msg);
/// <summary>
/// 客户端的socket
/// </summary>
private Socket m_socketClient;
/// <summary>
/// 服务器消息的缓存
/// </summary>
private byte[] m_serverMsgBuffer = new byte[SERVER_MSG_SZIE];
/// <summary>
/// 上一次连接服务器的时间
/// </summary>
private float m_lastConnectServerTime = CONNECT_SERVER_INIT_TIME;
/// <summary>
/// 连接服务器有效时间的间隔
/// </summary>
private const int CONNECT_SERVER_VALID_STRIDE_TIME = 5;
/// <summary>
/// 连接服务器的初始化时间
/// </summary>
private const int CONNECT_SERVER_INIT_TIME = -6;
/// <summary>
/// 服务器消息的大小
/// </summary>
private const int SERVER_MSG_SZIE = 1024 * 2;
public bool InConnect
{
get
{
if (m_socketClient == null)
return false;
return m_socketClient.Connected;
}
}
void Start()
{
ConnectServer();
}
/// <summary>
/// 连接服务器
/// </summary>
public void ConnectServer()
{
if (m_lastConnectServerTime + CONNECT_SERVER_VALID_STRIDE_TIME >= Time.time)
{
Debug.LogError("it need time to connecting server, please waitting....");
return;
}
m_lastConnectServerTime = Time.time;

try
{
//建立连接socket
m_socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//开始异步连接
m_socketClient.BeginConnect(IPAddress.Parse("120.25.1.87"),
9999,
new AsyncCallback(ConnectCallback), //定义回调函数代理
m_socketClient); //传递给回调函数的状态
}
catch (Exception e)
{
Debug.Log("connect server error, " + e.Message);
m_lastConnectServerTime = CONNECT_SERVER_INIT_TIME;
}
}
//连接方法的回调函数
private void ConnectCallback(IAsyncResult ar)
{
try
{
//从传递的状态中获取套接字,创建一个客户端套接字
Socket client = (Socket)ar.AsyncState;
//完成挂起的连接操作
client.EndConnect(ar);
Debug.Log("连接服务器成功,可以开始通话!");
client.BeginReceive(m_serverMsgBuffer, 0, 1000, 0, new AsyncCallback(receivecallback), client);
}
catch (Exception e)
{
Debug.Log("connect server fail, " + e.Message);
m_lastConnectServerTime = CONNECT_SERVER_INIT_TIME;
}
}
private void receivecallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int length = client.EndReceive(ar);
string msg = Encoding.UTF8.GetString(m_serverMsgBuffer, 0, length);

client.BeginReceive(m_serverMsgBuffer, 0, 1000, 0, new AsyncCallback(receivecallback), client);
//string astr =
//"{\"m_int\":11,\"m_float\":12.0,\"m_string\":\"dsd\",\"m_list\":[0,1,4,9,16,25,36,49,64,81],\"m_arr\":[\"str0\",\"str1\",\"str2\",\"str3\",\"str4\"]}";
Debug.Log("获取服务器消息:" + msg);
AA a = JsonConvert.DeserializeObject<AA>(msg);
for (int eleIdx = 0; eleIdx < a.m_arr.Length; eleIdx++)
{
Debug.LogWarning(a.m_arr[eleIdx]);
}
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
/// <summary>
/// 向服务器发送消息
/// </summary>
public void SendMsgToServer(String data)
{
AA a = new AA();
a.m_int = 11;
a.m_float = 12;
a.m_string = "dsd";
a.m_list = new List<int>();
for (int eleIdx = 0; eleIdx < 10; eleIdx++)
a.m_list.Add(eleIdx * eleIdx);
a.m_arr = new string[5];
for (int eleIdx = 0; eleIdx < 5; eleIdx++)
a.m_arr[eleIdx] = "str" + eleIdx;
string jsonStr = JsonConvert.SerializeObject(a);
//使用ASCII转换字符串为字节序列
byte[] byteData = Encoding.UTF8.GetBytes(jsonStr); //将字符串转换成字节序列
//开始向远端设备发送数据
m_socketClient.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(SendCallback), m_socketClient);
}
//发送方法的回调函数
private void SendCallback(IAsyncResult ar)
{
try
{
//从传递的状态中获取套接字,创建一个客户端套接字
Socket client = (Socket)ar.AsyncState;
//结束异步数据传输操作,返回传输的字节数
int bytesSent = client.EndSend(ar);
Debug.Log("给服务器发包成功:" + bytesSent);
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
}