Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

异步方法TCP客户端实现示例

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
public class NetAsyncMgr : MonoBehaviour
{
private static NetAsyncMgr instance;
public static NetAsyncMgr Instance => instance;
//和服务器进行链接的Socket
private Socket socket;
//接收消息的用的 缓存容器
private byte[] cacheByte = new byte[1024*1024];
private int cacheNum = 0;

// Start is called before the first frame update
void Awake()
{
instance = this;
//过场景不移除
DontDestroyOnLoad(this.gameObject);
}

// Update is called once per frame
void Update()
{

}
//链接服务器
public void Connect(string ip, int port)
{
if(socket!=null&&socket.Connected)
return;
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip), port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = ipPoint;
args.Completed += (socket, args) =>
{
if (args.SocketError == SocketError.Success)
{
print("链接成功");
//收消息
SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs();
receiveArgs.SetBuffer(cacheByte, 0, cacheByte.Length);
receiveArgs.Completed += ReceiveCallback;
this.socket.ReceiveAsync(receiveArgs);
}
else
{
print("链接失败"+args.SocketError);
}
};
socket.ConnectAsync(args);


}
//收消息完成的回调函数
private void ReceiveCallback(object sender, SocketAsyncEventArgs args)
{
if (args.SocketError == SocketError.Success)
{
//解析消息 暂时用字符串规则
print(Encoding.UTF8.GetString(args.Buffer, 0, args.BytesTransferred));
//继续去接收消息
args.SetBuffer(cacheByte, 0, cacheByte.Length);
//继续异步接收消息
if (socket!=null && this.socket.Connected)
socket.ReceiveAsync(args);
else
Close();

}
else
{
print("接收消息出错"+args.SocketError);
//关闭客户端链接
Close();
}
}
public void Close()
{
if (socket != null)
{
socket.Shutdown(SocketShutdown.Both);
socket.Disconnect(false);
socket.Close();
socket = null;
}
}

public void Send(string str)
{
if (socket != null && this.socket.Connected)
{
byte[] bytes = Encoding.UTF8.GetBytes(str);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.SetBuffer(bytes, 0, bytes.Length);
args.Completed += (socket, args) =>
{
if (args.SocketError != SocketError.Success)
{
print("发送消息失败"+args.SocketError);
Close();
}
};
this.socket.SendAsync(args);
}
else
{
Close();
}
}
}

评论