public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
slist = aa =>
{
listBox1.Items.Add(aa);
};
}
private int localPort = 6666;
private delegate void SetListBoxCallBack(string str);
private SetListBoxCallBack slist;
private static int PID = 6667;
private static ArrayList clientList = new ArrayList();
private void button1_Click(object sender, EventArgs e)
{
AcceptConnection();
}
//开始监听的回调函数
private void AcceptConnection()
{
try
{
Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
// 将 Socket 绑定到本地的终结点上
mainSocket.Bind(localEP);
// 开始侦听,最大的连接数是 50
mainSocket.Listen(50);
mainSocket.BeginAccept(new AsyncCallback(AcceptCallBack), mainSocket);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//接收连接的回调函数
private void AcceptCallBack(IAsyncResult iar)
{
try
{
Socket mainSocket = (Socket)iar.AsyncState;
// 调用EndAccept完成BeginAccept异步调用,返回一个新的Socket处理与客户的通信
Socket workerSocket = mainSocket.EndAccept(iar);
if (mainSocket.LocalEndPoint.ToString().IndexOf("6666") != -1)
{
int NewPid = PID++;
localPort = NewPid;
AcceptConnection();
SendData(System.Text.Encoding.Default.GetBytes("PID|" + NewPid), workerSocket);
}
else
{
// 存储客户端sokect
clientList.Add(workerSocket);
listBox1.Invoke(slist, workerSocket.RemoteEndPoint.ToString());
}
mainSocket.BeginAccept(new AsyncCallback(AcceptCallBack), mainSocket);
}
catch (Exception ex)
{
throw;
}
}
public void SendData(byte[] buffer, Socket workerSocket)
{
try
{
int left = buffer.Length;
int sndLen = 0;
workerSocket.BeginSend(buffer, sndLen, left, SocketFlags.None, new AsyncCallback(SendCallBack), workerSocket);
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message);
}
}
private void SendCallBack(IAsyncResult iar)
{
Socket workerSocket = (Socket)iar.AsyncState;
workerSocket.EndSend(iar);
}
private void button2_Click(object sender, EventArgs e)
{
byte[] buffer = System.Text.Encoding.Default.GetBytes("mesg|" + textBox1.Text);
int snLen = 0;
listBox2.Items.Add(textBox1.Text);
//while (true)
for (int i = 0; i < clientList.Count; i++)
{
int k = i;
Thread aa = new Thread(new ThreadStart(() =>
{
((Socket)clientList[k]).BeginSend(buffer, snLen, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), ((Socket)clientList[k]));
}));
aa.IsBackground = true;
aa.Start();
}
}
}