```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace TCPServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
public int serverPort;
public Socket ServerSocket;
public IPEndPoint localEp;
public void Listen()
{
int setPort = 33;
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ServerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
localEp = new IPEndPoint(IPAddress.Any, setPort);
try
{
ServerSocket.Bind(localEp);
ServerSocket.Listen(10);
ServerSocket.BeginAccept(new AsyncCallback(serverConnectRequest), ServerSocket);
btn_start.Text = "服务器已开启";
btn_start.Enabled = false;
}
catch (Exception ex)
{
}
}
public Socket server1, client1;
Dictionary<string, Socket> dic = new Dictionary<string, Socket> { };
public void serverConnectRequest(IAsyncResult ar)
{
try
{
server1 = (Socket)ar.AsyncState;
client1 = server1.EndAccept(ar);
string strDateLine = "欢迎登录到服务器";
Byte[] byteDateLine = System.Text.Encoding.UTF8.GetBytes(strDateLine);
EndPoint remote = client1.RemoteEndPoint;
client1.Send(byteDateLine, byteDateLine.Length, 0);
string client1IP = client1.RemoteEndPoint.ToString();
dic.Add(client1IP, client1);
listBoxOnlineList.Items.Add(client1IP);
server1.BeginAccept(new AsyncCallback(serverConnectRequest), server1);
while (true)
{
int recv = client1.Receive(byteDateLine);
string stringdata = Encoding.UTF8.GetString(byteDateLine, 0, recv);
rtb_rec.Text = stringdata;
string ip = client1.RemoteEndPoint.ToString();
if (stringdata == "STOP")
{
MessageBox.Show(ip + " " + "已从服务器断开","发来stop");
listBoxOnlineList.Items.Remove(client1.RemoteEndPoint.ToString());
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"客户端报错1");
}
}
public string selectClient;
private void btn_start_Click(object sender, EventArgs e)
{
Listen();
}
private void btn_send_Click(object sender, EventArgs e)
{
sendBroadMsg();
}
public void sendBroadMsg()
{
try
{
string sendMsg1 = rtb_send.Text ;
byte[] sendData = Encoding.UTF8.GetBytes(sendMsg1);
for (int i = 0; i < listBoxOnlineList.Items.Count; i++)
{
selectClient = listBoxOnlineList.Items[i].ToString();
dic[selectClient].Send(sendData);
}
}
catch (Exception)
{
listBoxOnlineList.Items.Remove(selectClient);
}
}
}
}