【转】Unity3d中的Tcpsocket通信(开源)HiSocket_unity
如何使⽤
可以从此链接下载最新的unity package:
功能
详情
细节
private IPackage _packer = new Packer();
void Test()
{
_tcp = new TcpConnection(_packer);
}
public class Packer : IPackage
{
public void Unpack(IByteArray reader, Queue<byte[]> receiveQueue)
{
//add your unpack logic here
}
public void Pack(Queue<byte[]> ndQueue, IByteArray writer)
{
/
/ add your pack logic here
}
}
1
2
3
4
5
6
7
8
简易图片
9
10
11
12
13
14
15
16
17
18
连接
_tcp.Connect("127.0.0.1", 7777);
1
断开连接
当不再运⾏时需要主动调⽤接⼝断开与服务器的连接(⽐如响应unity的onapplicationquit执⾏时)
早c
void OnApplicationQuit()
{
_tcp.DisConnect();
}
1
2
3
4
连接状态变化
如果想获取当前的连接状态,可以订阅连接状态事件.
1
2
3
4
城上
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
发送消息
1
2
3
4void Test()
{
_tcp.StateChangeEvent += OnState;
}
void OnState(SocketState state)
{
Debug.Log("current state is: " + state);
if (state == SocketState.Connected)
{
Debug.Log("connect success");
//can nd or receive message
}
el if (state == SocketState.DisConnected) {
Debug.Log("connect failed");
}
el if (state == SocketState.Connecting) {
事业合伙人
Debug.Log("connecting");
}
}
void Test()
{
var bytes = BitConverter.GetBytes(100);
_tcp.Send(bytes);
}
5
接受消息
西安体育大学You can regist receiveevent and when message come from rver, this event will be fire.
void Test()
{
_tcp.ReceiveEvent += OnReceive;
}
void OnReceive(byte[] bytes)
{
Debug.Log("receive msg: " + BitConverter.ToInt32(bytes, 0));
}
1
2
3
4
5
6
7
8
封包和解包
最初创建连接时我们定义了⼀个packer来分割数据包,当发送消息时我们在数据头部插⼊消息长度/当接收到消息时我们根据头部的消息长度获得数据包的⼤⼩.
private bool _isGetHead = fal;
private int _bodyLength;
public void Unpack(IByteArray reader, Queue<byte[]> receiveQueue)
{
if (!_isGetHead)
{
if (reader.Length >= 2)//2 is example, get msg's head length
{
var bodyLengthBytes = reader.Read(2);
_bodyLength = BitConverter.ToUInt16(bodyLengthBytes, 0);
}
el
{
if (reader.Length >= _bodyLength)//get body
{
var bytes = reader.Read(_bodyLength);
receiveQueue.Enqueue(bytes);
_isGetHead = fal;
}
}
}
}
public void Pack(Queue<byte[]> ndQueue, IByteArray writer)
{
var bytesWaitToPack = ndQueue.Dequeue();
UInt16 length = (UInt16)bytesWaitToPack.Length;//get head lenth
var bytesHead = BitConverter.GetBytes(length);
writer.Write(bytesHead);//write head
writer.Write(bytesWaitToPack);//write body
}
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
Udp
Udp connection
如果创建upd连接,需要指定发送接收缓冲区⼤⼩.
_udp = new UdpConnection(1024);
1
Ping