服务器端
Socket socketWatch = null; Thread threadWatch = null; Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>(); Dictionary<string, Thread> dicThread = new Dictionary<string, Thread>(); socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address = IPAddress.Parse(ipTb.Text.Trim()); IPEndPoint endPoint = new IPEndPoint(address, int.Parse(portTb.Text.Trim())); try { socketWatch.Bind(endPoint); } catch (Exception ex) { MessageBox.Show("异常:" + ex.Message); return; } socketWatch.Listen(10); threadWatch = new Thread(WatchConnecting); threadWatch.IsBackground = true; threadWatch.Start();
//为每一个连进来的socket创建线程 private void WatchConnecting() { while (true) { Socket sokConnection = socketWatch.Accept(); lb.Items.Add(sokConnection.RemoteEndPoint.ToString()); dicSocket.Add(sokConnection.RemoteEndPoint.ToString(), sokConnection); ShowMsg("客户端连接成功"); Thread th = new Thread(RecMsg); th.IsBackground = true; th.Start(sokConnection); dicThread.Add(sokConnection.RemoteEndPoint.ToString(), th); } }
信息接收
private void RecMsg(object sokConnection) { Socket sokClient = sokConnection as Socket; while (true) { byte[] arrMsgRec = new byte[1025 * 1024 * 2]; int length = -1; try { length = sokClient.Receive(arrMsgRec); } catch (Exception ex) { ShowMsg("异常:" + ex.Message); dicThread.Remove(sokClient.RemoteEndPoint.ToString()); dicThread.Remove(sokClient.RemoteEndPoint.ToString()); lb.Items.Remove(sokClient.RemoteEndPoint.ToString()); } if (arrMsgRec[0] == 0)//msg { string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, arrMsgRec.Length - 1); ShowMsg(strMsg); } if (arrMsgRec[0] == 1)//file { SaveFileDialog sfd = new SaveFileDialog(); if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { string fileSavePath = sfd.FileName; using (FileStream fs = new FileStream(fileSavePath, FileMode.Create)) { fs.Write(arrMsgRec, 1, arrMsgRec.Length - 1); ShowMsg("文件保存成功"); } } } } }
信息发送
byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg); byte[] arrSendMsg = new byte[arrMsg.Length + 1]; arrSendMsg[0] = 0; Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length); string strKey = lb.Text.Trim(); if (string.IsNullOrEmpty(strKey)) { dicSocket[strKey].Send(arrSendMsg); ShowMsg(strMsg); msgStb.Clear(); }
客户端
//根据目标ip直接连接 IPAddress ip = IPAddress.Parse(iptb.Text.Trim()); IPEndPoint endPoint=new IPEndPoint(ip,int.Parse(potb.Text.Trim())); socketClient=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); try { ShowMsg("与服务器连接中..."); socketClient.Connect(endPoint); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } ShowMsg("与服务器连接成功..."); threadClient = new Thread(RecMsg); threadClient.IsBackground = true; threadClient.Start();