List<Socket> SocketClientList = new List<Socket>();
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);
serverSocket.Bind(ipEndpoint);
serverSocket.Listen(10);
ThreadPool.QueueUserWorkItem(new WaitCallback(GetAccept), serverSocket);
}
private void GetAccept(object state)
{
Socket serverSocket = state as Socket;
while (true)
{
Socket socketClient = serverSocket.Accept();
socketClient.Send(Encoding.Default.GetBytes("收到一个连接————"));
SocketClientList.Add(socketClient);
ThreadPool.QueueUserWorkItem(new WaitCallback(ReceiveData), socketClient);
}
}
private void ReceiveData(object obj) {
Socket socketClient = obj as Socket;
byte[] buffer = new byte[1024*1024];
while (true) {
int l=0;
try //捕获异常退出
{
l= socketClient.Receive(buffer, 0, buffer.Length, SocketFlags.None);
}
catch {
SocketClientList.Remove(socketClient);
return;
//异常退出
}
//在退出前会发送一个字消息 正常退出
if (l == 0)
{
socketClient.Shutdown(SocketShutdown.Both);
socketClient.Close();
SocketClientList.Remove(socketClient);
return;
}
string msgfromclient = Encoding.Default.GetString(buffer, 0, l);
//在下面添加收到消息的逻辑
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (Socket socket in SocketClientList)
{
if(socket.Connected)
{
socket.Send(Encoding.Default.GetBytes(("data" + DateTime.Now.ToString())));
}
}
}