public List<User> users = new List<User>();
Socket socket;
//初始化服务器
public void InitSever()
{
//创建一个Socket对象
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//将把通信的地址和端口绑定到 socket 上
socket.Bind(new IPEndPoint(IPAddress.Any, 2003));
//链接最大限制
socket.Listen(10);
Console.WriteLine("服务器已开启");
//ThreadPool.QueueUserWorkItem(OnAccept);
//开线程
//Thread thread = new Thread(OnAccept);
//thread.Start();
//异步等待连接
socket.BeginAccept(AsyOnAccept, null);
}
//异步发消息给客户端
public void AsyOnSendClient(byte[] data,User cli)
{
cli.socket.BeginSend(data, 0, data.Length, SocketFlags.None, AsyOnSend, cli);
}
private void AsyOnSend(IAsyncResult ar)
{
User cli = ar.AsyncState as User;
int len=cli.socket.EndSend(ar);
Console.WriteLine("发送到客户端得小时长度是:"+len);
}
private void AsyOnAccept(IAsyncResult ar)
{
try
{
Socket socket_cli=socket.EndAccept(ar);
IPEndPoint iPEnd=socket_cli.RemoteEndPoint as IPEndPoint;
User u = new User();
u.socket = socket_cli;
u.name = iPEnd.Port.ToString();
users.Add(u);
Console.WriteLine("用户"+u.name+"链接");
//再次开启等待新用户链接
socket.BeginAccept(AsyOnAccept, null);
//异步接收消息
socket_cli.BeginReceive(u.data,0,u.data.Length,SocketFlags.None,AsyOnReceive,u);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
//异步接受消息
private void AsyOnReceive(IAsyncResult ar)
{
try
{
User cli = ar.AsyncState as User;
int len =cli.socket.EndReceive(ar);
if(len>0)
{
Console.WriteLine("收到消息长度:" + len);
}
cli.socket.BeginReceive(cli.data, 0, cli.data.Length, SocketFlags.None, AsyOnReceive, cli);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
/*同步
开启线程 用户连接*/
private void OnAccept()
{
while (true)
{
//客户端链接服务器
Socket smallSocket = socket.Accept();
IPEndPoint point = smallSocket.RemoteEndPoint as IPEndPoint;
User u = new User();
u.socket = smallSocket;
u.name = smallSocket.RemoteEndPoint.ToString();
users.Add(u);
Console.WriteLine("用户{0}链接成功", point.Address);
while (true)
{
//服务器接收客户端
smallSocket.Receive(u.data);
Console.WriteLine("收到{0}", UTF8Encoding.UTF8.GetString(u.data));
//服务器回复客户端
Sendstr(u.data, u);
}
}
}
//回复客户端
private void Sendstr(byte[] data, User u)
{
u.socket.Send(data);
}