Socket socketWatch = obj as Socket;
while (true)
{
try
{
//等待客户端的连接,同时会创建一个与其通信的socket
socketCommunication = socketWatch.Accept();
clientCommunicationSocketList.Add(socketCommunication);
dicSocket.Add(socketCommunication.RemoteEndPoint.ToString(), socketCommunication);
//cboUsers.Items.Add(socketCommunication.RemoteEndPoint.ToString());
//解决跨线程访问cboUsers所导致的问题
if(cboUsers.InvokeRequired)
{
cboUsers.Invoke(new Action(() => { cboUsers.Items.Add(socketCommunication.RemoteEndPoint.ToString()); }), null);
}
else
{
cboUsers.Items.Add(socketCommunication.RemoteEndPoint.ToString());
}
ShowMsg(socketCommunication.RemoteEndPoint.ToString() ":连接成功");
Thread thread = new Thread(Receive);
thread.IsBackground = true;
thread.Start(socketCommunication);
}
catch
{
}
}
}
void Receive(object obj)
{
Socket socketCommunication = obj as Socket;
byte[] buffer = new byte[1024 * 1024 * 2];
while (true)
{
try
{
//r表示实际接收到的字节数
int r = socketCommunication.Receive(buffer);
if(r==0)
{
//break;
socketCommunication.Shutdown(SocketShutdown.Both);
socketCommunication.Close();
return;
}
string str = Encoding.UTF8.GetString(buffer, 0, r);
//显示消息格式:客户端IP 端口:消息
ShowMsg(socketCommunication.RemoteEndPoint.ToString() ":" str);
}
catch
{
}
}
}
void ShowMsg(string str)
{
if (txtLog.InvokeRequired)
{
txtLog.Invoke(new Action<string>(s =>
{
txtLog.AppendText(s "\r\n");
}), str);
}
else
{
//txtLog.Text = str "\r\n" txtLog.Text;
txtLog.AppendText(str "\r\n");
}
}
评论