Socket socket;
public void InitServer()
{
//初始化 网络 流字节 协议
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Any, 666)); //绑定
socket.Listen(1000);//侦听
Console.WriteLine("服务器开启啦");
socket.BeginAccept(OnAccept, null);//异步加载
}
private void OnAccept(IAsyncResult ar)
{
try
{
Socket socket_cli = socket.EndAccept(ar);
IPEndPoint iPEnd = socket_cli.RemoteEndPoint as IPEndPoint;
Console.WriteLine("有人连接了");
socket.BeginAccept(OnAccept, null);
Client client = new Client();
client.socket = socket_cli;
socket_cli.BeginReceive(client.data, 0, client.data.Length, SocketFlags.None, OnReceive, client);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void OnReceive(IAsyncResult ar)
{
try
{
Client client = ar.AsyncState as Client;
//真实长度
int len = client.socket.EndReceive(ar);
// Console.WriteLine("收到消息长度" + len);
if (len > 0)
{
byte[] rdata = new byte[len];
Buffer.BlockCopy(client.data, 0, rdata, 0, len);
while (rdata.Length > 4)
{
int bodylen = BitConverter.ToInt32(rdata, 0);
byte[] bodydata = new byte[bodylen];
Buffer.BlockCopy(rdata, 4, bodydata, 0, bodydata.Length);
int msgid = BitConverter.ToInt32(bodydata, 0);
byte[] info = new byte[bodylen - 4];
Buffer.BlockCopy(bodydata, 4, info, 0, bodylen - 4);
MsgData msgData = new MsgData();
msgData.data = info;
msgData.client = client;
MessageManager<MsgData>.Ins.OnBroadCast(msgid, msgData);
int sylen = rdata.Length - 4 - bodylen;
byte[] sydata = new byte[sylen];
Buffer.BlockCopy(rdata, 4 + bodylen, sydata, 0, sylen);
rdata = sydata;
}
}
client.socket.BeginReceive(client.data, 0, client.data.Length, SocketFlags.None, OnReceive, client);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
public void OnSendServer(int id, byte[] data, Client client)
{
int head = 4 + data.Length;
byte[] enddata = new byte[0];
enddata = enddata.Concat(BitConverter.GetBytes(head)).Concat(BitConverter.GetBytes(id)).Concat(data).ToArray();
client.socket.BeginSend(enddata, 0, enddata.Length, SocketFlags.None, OnSend, client);
}
private void OnSend(IAsyncResult ar)
{
Client client = ar.AsyncState as Client;
int len = client.socket.EndSend(ar);
Console.WriteLine("发送到客户端消息长度" + len);
}