using System;
using System.Net.Sockets;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
namespace UnityCommon
{
public class ClientSocket
{
private Socket init()
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 接收的消息数据包大小限制为 0x4000 byte, 即16KB
m_recvBuff = new byte[0x4000];
m_recvCb = new AsyncCallback(RecvCallBack);
return clientSocket;
}
///
/// 连接服务器
///
/// ip地址
/// 端口号
public void Connect(string host, int port, Action onFailed)
{
if (m_socket == null)
m_socket = init();
try
{
Debug.Log("connect: " + host + ":" + port);
m_socket.SendTimeout = 3;
m_socket.Connect(host, port);
connected = true;
}
catch (Exception ex)
{
Debug.LogError(ex);
onFailed?.Invoke();
}
}
///
/// 发送消息
///
public void SendData(byte[] bytes)
{
NetworkStream netstream = new NetworkStream(m_socket);
netstream.Write(bytes, 0, bytes.Length);
}
///
/// 尝试接收消息(每帧调用)
///
public void BeginReceive()
{
m_socket.BeginReceive(m_recvBuff, 0, m_recvBuff.Length, SocketFlags.None, m_recvCb, this);
}
///
/// 当收到服务器的消息时会回调这个函数
///
private void RecvCallBack(IAsyncResult ar)
{
var len = m_socket.EndReceive(ar);
byte[] msg = new byte[len];
Array.Copy(m_recvBuff, msg, len);
var msgStr = System.Text.Encoding.UTF8.GetString(msg);
// 将消息塞入队列中
m_msgQueue.Enqueue(msgStr);
// 将buffer清零
for (int i = 0; i < m_recvBuff.Length; ++i)
{
m_recvBuff[i] = 0;
}
}
///
/// 从消息队列中取出消息
///
///
public string GetMsgFromQueue()
{
if (m_msgQueue.Count > 0)
return m_msgQueue.Dequeue();
return null;
}
///
/// 关闭Socket
///
public void CloseSocket()
{
Debug.Log("close socket");
try
{
m_socket.Shutdown(SocketShutdown.Both);
m_socket.Close();
}
catch (Exception e)
{
//Debug.LogError(e);
}
finally
{
m_socket = null;
connected = false;
}
}
public bool connected = false;
private byte[] m_recvBuff;
private AsyncCallback m_recvCb;
private Queue m_msgQueue = new Queue();
private Socket m_socket;
//public static void AcceptClient(Socket server)
//{
// Socket client = null;
// do
// {
// try
// {
// client = server.Accept();
// if (client != null)
// {
// Console.WriteLine("客户 \'{0}\' 已连接。", client.RemoteEndPoint.ToString());
// Task.Run(() => ReceiveData(client)).Wait(100);
// }
// }
// catch (Exception ex)
// {
// client = null;
// }
// } while (client != null);
//}
public static void ReceiveData(Socket socket) // 接收消息函数(传入一个socket对象)
{
try
{
MessageProtocol mp = null;
int ReceiveLength = 0;
byte[] staticReceiveBuffer = new byte[65536]; // 接收缓冲区(固定长度)
byte[] dynamicReceiveBuffer = new byte[] { }; // 累加数据缓存(不定长)
do
{
ReceiveLength = socket.Receive(staticReceiveBuffer); // 同步接收数据
dynamicReceiveBuffer = CombineBytes(dynamicReceiveBuffer, 0, dynamicReceiveBuffer.Length, staticReceiveBuffer, 0, ReceiveLength); // 将之前多余的数据与接收的数据合并,形成一个完整的数据包
if (ReceiveLength <= 0) // 如果接收到的数据长度小于0(通常表示socket已断开,但也不一定,需要进一步判断,此处可以忽略)
{
break; // 终止接收循环
}
else if (dynamicReceiveBuffer.Length < MessageProtocol.HEADLENGTH) // 如果缓存中的数据长度小于协议头长度,则继续接收
{
continue; // 跳过本次循环继续接收数据
}
else // 缓存中的数据大于等于协议头的长度(dynamicReadBuffer.Length >= 6)
{
var headInfo = MessageProtocol.GetHeadInfo(dynamicReceiveBuffer); // 解读协议头的信息
while (dynamicReceiveBuffer.Length - MessageProtocol.HEADLENGTH >= headInfo.DataLength) // 当缓存数据长度减去协议头长度大于等于实际数据的长度则进入循环进行拆包处理
{
mp = new MessageProtocol(dynamicReceiveBuffer); // 拆包
dynamicReceiveBuffer = mp.MoreData; // 将拆包后得出多余的字节付给缓存变量,以待下一次循环处理数据时使用,若下一次循环缓存数据长度不能构成一个完整的数据包则不进入循环跳到外层循环继续接收数据并将本次得出的多余数据与之合并重新拆包,依次循环。
headInfo = MessageProtocol.GetHeadInfo(dynamicReceiveBuffer); // 从缓存中解读出下一次数据所需要的协议头信息,已准备下一次拆包循环,如果数据长度不能构成协议头所需的长度,拆包结果为0,下一次循环则不能成功进入,跳到外层循环继续接收数据合并缓存形成一个完整的数据包
if (mp.Command == 0 && mp.Param == 0)
{
socket.Send(new MessageProtocol(0, 0, Encoding.UTF8.GetBytes("Goodbye\r\n再见!")).GetBytes());
return;
}
ResponseRequest(socket, mp.GetMessage());
} // 拆包循环结束
}
} while (ReceiveLength > 0);
}
finally
{
Console.WriteLine("客户 \'{0}\' 已离开", socket.RemoteEndPoint.ToString());
socket.Close();
}
}
public static void ResponseRequest(Socket client, (byte Command, byte Param, int DataLength, byte[] MessageData) message)
{
string text = Encoding.UTF8.GetString(message.MessageData);
Console.WriteLine("客户 \'{0}\' 发来信息: \'{1}\'。", client.RemoteEndPoint.ToString(), text);
text = new String(text.Reverse().ToArray());
client.Send(new MessageProtocol(1, 1, Encoding.UTF8.GetBytes(text)).GetBytes());
}
public static byte[] CombineBytes(byte[] firstBytes, int firstIndex, int firstLength, byte[] secondBytes, int secondIndex, int secondLength)
{
byte[] bytes = null;
MemoryStream ms = new MemoryStream();
ms.Write(firstBytes, firstIndex, firstLength);
ms.Write(secondBytes, secondIndex, secondLength);
bytes = ms.ToArray();
ms.Close();
return (bytes);
}
}
}