1、介绍
前面的章节中制作的小游戏中并没有处理TCP数据流的粘包拆包的问题。这一节对其进行处理。程序采用简单的Echo程序。解决粘包问题采用的方法为长度法。
2、客户端
采用异步socket进行数据的收发。接收数据的处理思路为:1、判断接收缓冲区的数据长度是否超过设定的数据长度包头headerSize,如果超过则读取包头长度,解析出数据包的长度;然后判断当前缓冲区的字节数是否大于等于一个数据包,若是则处理,否则继续接收。
直接上代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System;
using System.Net.Sockets;
public class Echo : MonoBehaviour
{
Socket socket;
int bufferSize = 1024;
byte[] recvBuff;
int bufferCount = 0;
int headerSize = 4;
bool startSendMsg = false;
private void Start()
{
recvBuff = new byte[bufferSize];
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("127.0.0.1", 8888);
socket.BeginReceive(recvBuff, bufferCount, bufferSize - bufferCount, SocketFlags.None,
ReceiveCallBack, socket);
}
void ReceiveCallBack(IAsyncResult ar)
{
try
{
Socket socket = (Socket)ar.AsyncState;
int count = socket.EndReceive(ar);
bufferCount += count;
HandleReceiveData();
socket.BeginReceive(recvBuff, bufferCount, bufferSize - bufferCount, SocketFlags.None,
ReceiveCallBack, socket);
}
catch (SocketException ex)
{
Debug.Log("socket receive failed" + ex.ToString());
}
}
void HandleReceiveData()
{
Debug.Log("接收缓冲区字节数 =" + bufferCount);
// 检查数据长度是否超过包头
if (bufferCount < headerSize)
return;
// 读取包头长度 -- 从缓冲区的开头读取4字节
int bodyLength = BitConverter.ToInt32(recvBuff, 0);
// 检查是否足够一条信息
if (bufferCount < headerSize + bodyLength)
return;
// 处理一条消息
string data = System.Text.Encoding.UTF8.GetString(recvBuff, headerSize, bodyLength);
Debug.Log("receive data = " + data);
// 更新缓冲区信息
int start = headerSize + bodyLength;
// 移动的字节数
int count = bufferCount - start;
// 缓冲区前移 -- Copy函数对应C/C++中的memmove, 不是memcopy
// 相当于将缓冲区的数据从start开始的count字节数据往前推到0
Array.Copy(recvBuff, start, recvBuff, 0, count);
bufferCount -= start;
// 继续处理消息
HandleReceiveData();
}
public void Send()
{
// 发送数据
string sendStr= "hello Python";
// 组装消息
byte[] bodyBytes = System.Text.Encoding.Default.GetBytes(sendStr);
short length = (short)bodyBytes.Length;
byte[] lenBytes = BitConverter.GetBytes(length);
byte[] sendBytes = lenBytes.Concat(bodyBytes).ToArray();
// 异步Send
socket.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, SendCallBack, socket);
string sendata = BitConverter.ToString(sendBytes);
Debug.Log("Send body length: " + length);
Debug.Log("Send data: " + sendata);
}
public void SendCallBack(IAsyncResult ar)
{
Socket socket = (Socket)ar.AsyncState;
int count = socket.EndSend(ar);
// startSendMsg = false;
// 后续处理
}
public void OnButtonStartClick()
{
startSendMsg = true;
}
private void Update()
{
if (!startSendMsg)
return;
Send();
}
}
在原书上的包头设定的字节数为2字节,但是因为我使用的服务器是用python编写,在python中使用struct打包字节流的时候,int数据占4字节,并且好像没有int16这样的数据类型,所以这里的headerSize设定为4字节。
3、服务端
服务端直接上代码,即插即用:
# Handle The TCP problem
import socket
import time
import struct
def parse_msg_length(head):
# 解析头两个字节的包头大小,得到数据包的长度。
# 因为recv直接返回的是字符串,所以需要用ord将其转换为数值类型
# 因为是2个字节,一个字节是2**8=256,相当于256进制
length = 0
for i in range(len(head)):
length += ord(head[i]) * 256 ** i
return length
def handle_message(read_buffer):
# 判断缓冲区大小是否大于包头大小
buffer_count = len(read_buffer)
if buffer_count < head_size:
return False, 0
# 判断缓冲区中是否存够了一条完整的数据
msg_body_size = parse_msg_length(read_buffer[0:head_size])
if buffer_count < head_size + msg_body_size:
return False, 0
# 处理数据
data = read_buffer[head_size:msg_body_size+head_size]
print 'data:', data
# 返回,将已经处理的数据丢弃
return True, msg_body_size
# server socket
ip = "127.0.0.1"
port = 8888
server_address = (ip, port)
buffer_size = 1024
head_size = 2
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(server_address)
server.listen(1)
read_buffer = ""
print "Waiting for Connection."
while True:
connection, client_address = server.accept()
print "client connected: ", client_address
while True:
try:
# 将发送的数据用struct类型打包成字节流
msg_body = "Hello Unity"
pack_format = 'I' + str(len(msg_body)) + 's'
send_data = (len(msg_body), msg_body)
send_bytes = struct.pack(pack_format, *send_data)
connection.send(send_bytes)
# time.sleep(1)
# 接收数据,recv返回的是字符串,直接加在read_buffer后,字符串作为缓冲区
# 字符串作为缓冲区的好处就是不需要数据包的大小超过了缓冲区的大小而导致要扩容
receive_data = connection.recv(buffer_size)
if receive_data:
read_buffer += receive_data
result, length = handle_message(read_buffer)
if result:
read_buffer = read_buffer[head_size + length:]
else:
pass
print 'read_buffer: ', read_buffer
else:
connection.close()
break
except socket.error:
connection.close()
4、结语
后续还要处理的问题有:大小端兼容、send发包不完整以及线程冲突的问题。
好好学习天天向上!