using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Net.Sockets;
namespace ASyncSocketServer
{
class ClientInfo//客户端信息类
{
const int BUFFER_SIZE = 1024;//缓冲区的大小
public Socket client;//当前客户端保持连接的套接字
public byte[] buffer;//这个套接字接收到的数据
public ClientInfo(Socket client)
{
this.client = client;
buffer = new byte[BUFFER_SIZE];
}
public string getInfo()//返回这个客户端的ip和端口字符串
{
return client.RemoteEndPoint.ToString();
}
}
class Program
{
//所有的连接套接字的信息
static List<ClientInfo> clientInfos = new List<ClientInfo>();
static void Main(string[] args)
{
Socket listenSocket = null;
try {
IPAddress ipAddr = IPAddress.Parse("127.0.0.1");
Console.WriteLine("ip地址创建成功!");
IPEndPoint ipEP = new IPEndPoint(ipAddr, 7777);
Console.WriteLine("ip终结点创建成功!");
listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("监听套接字创建成功!");
listenSocket.Bind(ipEP);
Console.WriteLine("绑定成功!");
listenSocket.Listen(5);
Console.WriteLine("监听成功!");
//开始承认连接
listenSocket.BeginAccept(new AsyncCallback(Accept), listenSocket);
Console.WriteLine("服务器启动成功!");
}catch(Exception e)
{
Console.WriteLine("服务器启动过程出错了!" + e.Message);
if (listenSocket != null) { }
listenSocket.Close();
}
Console.ReadLine();
}
static void Accept(IAsyncResult iar)
{
Console.WriteLine("Accept:有连接了!");
//得到监听的套接字
Socket listenSocket = iar.AsyncState as Socket;
try {
//确认这次连接
Socket client = listenSocket.EndAccept(iar);
Console.WriteLine("Accept:确认连接成功!");
ClientInfo ci = new ClientInfo(client);
//保存这个套接字
clientInfos.Add(ci);
Console.WriteLine("Accept:现在一共有" + clientInfos.Count);
//接收这个客户端发来的数据
client.BeginReceive(ci.buffer, 0, ci.buffer.Length, SocketFlags.None, new AsyncCallback(Receive), ci);
Console.WriteLine("Accept:开始接收这个客户端的信息!");
//广播出去
//继续承认连接
listenSocket.BeginAccept(new AsyncCallback(Accept), listenSocket);
}
catch(Exception e)
{
Console.WriteLine("Accept:有错误了!"+e.Message);
}
Console.WriteLine("Accept:结束了!");
}
static void Receive(IAsyncResult iar)
{
//得到当前发数据的客户端信息
ClientInfo ci = iar.AsyncState as ClientInfo;
try {
//确认接收
int len = ci.client.EndReceive(iar);
//判断客户端是否已经断开
if (len <= 0)
{
Console.WriteLine(ci.getInfo() + "Receive:这个客户端断开了!");
//移除这个客户端的信息
ci.client.Close();
clientInfos.Remove(ci);
//广播这个客户走的信息给其它
return;
}
string str = Encoding.UTF8.GetString(ci.buffer, 0, len);
Console.WriteLine(ci.getInfo() + "Receive:来数据了:" + str);
str = ci.getInfo() + "说:" + str;
//广播信息
foreach (ClientInfo c in clientInfos)
{
//判断是否是自己
c.client.Send(Encoding.UTF8.GetBytes(str));
}
}catch(Exception e)
{
Console.WriteLine( "Receive:"+e.Message);
return;
}
//继续接收这个客户端发来的数据
ci.client.BeginReceive(ci.buffer, 0, ci.buffer.Length, SocketFlags.None, new AsyncCallback(Receive), ci);
}
}
}
异步套接字
最新推荐文章于 2021-02-21 16:44:57 发布