- 服務器端
1、開啟監聽

//開啟監聽 private void button1_Click(object sender, EventArgs e) { //當點擊開始監聽的時候 在服務器端創建一個負責監聽IP地址和端口號的Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //獲取ip地址 IPAddress ip = IPAddress.Parse(this.txt_IP.Text.Trim()); //創建端口號 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txt_Port.Text.Trim())); //綁定IP地址和端口號 socketWatch.Bind(point); //開始監聽:設置最大可以同時連接多少個請求 socketWatch.Listen(10); this.txt_Log.AppendText("監聽成功" + " \r \n"); //實例化回調 setCallBack = new SetTextValueCallBack(SetTextValue); //修改textbox receiveCallBack = new ReceiveMsgCallBack(ReceiveMsg); //修改textbox setCmbCallBack = new SetCmbCallBack(AddCmbItem); //修改combox sendCallBack = new SendFileCallBack(SendFile); //發送信息 //創建線程 AcceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen)); //創建監聽參數{監聽} AcceptSocketThread.IsBackground = true; AcceptSocketThread.Start(socketWatch); } /// <summary> /// 監聽等待PC端的連接,創建通信用的Socket /// </summary> /// <param name="obj"></param> private void StartListen(object obj) { Socket socketWatch = obj as Socket; //等待客戶端的連接,並且創建一個用於通信的Socket socketSend = socketWatch.Accept(); //獲取遠程主機的ip地址和端口號 string strIp = socketSend.RemoteEndPoint.ToString(); dicSocket.Add(strIp, socketSend); this.cmb_Socket.Invoke(setCmbCallBack, strIp);//將遠程主機ip地址及 通訊Socket添加到combox string strMsg = "遠程主機:" + socketSend.RemoteEndPoint + "連接成功"; //使用回調 txt_Log.Invoke(setCallBack, strMsg); //定義接收客戶端消息的線程 Thread threadReceive = new Thread(new ParameterizedThreadStart(Receive)); threadReceive.IsBackground = true; threadReceive.Start(socketSend); } /// <summary> ///監聽消息 /// </summary> /// <param name="obj"></param> private void Receive(object obj) { Socket socketSend = obj as Socket; //客戶端連接成功后,服務器接收客戶端發送的消息 byte[] buffer = new byte[1024*100]; //實際接收到的有效字節數 int count = socketSend.Receive(buffer); if (count == 0)//count 表示客戶端關閉,要退出循環 { } else { string str = Encoding.Default.GetString(buffer, 0, count); string strReceiveMsg = "接收:" + socketSend.RemoteEndPoint + "發送的消息:" + str; txt_Log.Invoke(receiveCallBack, strReceiveMsg); } }
2、發送消息

/// <summary> /// 發送消息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button5_Click(object sender, EventArgs e) { try { string strMsg = this.txt_Msg.Text.Trim(); byte[] buffer = Encoding.Default.GetBytes(strMsg); List<byte> list = new List<byte>(); list.Add(0); list.AddRange(buffer); //將泛型集合轉換為數組 byte[] newBuffer = list.ToArray(); //獲得用戶選擇的IP地址 string ip = this.cmb_Socket.SelectedItem.ToString(); dicSocket[ip].Send(newBuffer); } catch (Exception ex) { MessageBox.Show("給客戶端發送消息出錯:" + ex.Message); } }
3、停止監聽

/// <summary> /// 停止監聽 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { socketWatch.Close(); socketSend.Close(); AcceptSocketThread.Abort(); threadReceive.Abort(); }
- 客戶端
1、連接服務器

/// <summary> /// 連接服務器 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { try { socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse(this.txt_IP.Text.Trim()); socketSend.Connect(ip, Convert.ToInt32(this.txt_Port.Text.Trim())); //實例化回調 setCallBack = new SetTextCallBack(SetValue); receiveCallBack = new ReceiveMsgCallBack(SetValue); this.txt_Log.Invoke(setCallBack, "連接成功"); //開啟一個新的線程不停的接收服務器發送消息的線程 threadReceive = new Thread(new ThreadStart(Receive)); //設置為后台線程 threadReceive.IsBackground = true; threadReceive.Start(); } catch (Exception ex) { MessageBox.Show("連接服務端出錯:" + ex.ToString()); } }
2、發送消息

/// <summary> /// 發送消息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { try { string strMsg = this.txt_Msg.Text.Trim(); byte[] buffer = new byte[2048]; buffer = Encoding.Default.GetBytes(strMsg); int receive = socketSend.Send(buffer); } catch (Exception ex) { MessageBox.Show("發送消息出錯:" + ex.Message); } }
3、接收消息

/// <summary> /// 監聽服務器發送消息 /// </summary> private void Receive() { try { byte[] buffer = new byte[2048]; //實際接收到的字節數 int r = socketSend.Receive(buffer); if (r == 0) { } else { //判斷發送的數據的類型 if (buffer[0] == 0)//表示發送的是文字消息 { string str = Encoding.Default.GetString(buffer, 1, r - 1); this.txt_Log.Invoke(receiveCallBack, "接收遠程服務器:" + socketSend.RemoteEndPoint + "發送的消息:" + str); } //表示發送的是文件 if (buffer[0] == 1) { if (buffer[1] == 0) { SaveFileDialog sfd = new SaveFileDialog(); sfd.InitialDirectory = @""; sfd.Title = "請選擇要保存的文件"; sfd.Filter = "所有文件|*.*"; sfd.ShowDialog(this); strPath = sfd.FileName; } using (FileStream fsWrite = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write)) { fsWrite.Write(buffer, 2, r - 2); } MessageBox.Show("保存文件成功"); } } } catch (Exception ex) { MessageBox.Show("接收服務端發送的消息出錯:" + ex.ToString()); } }
4、斷開連接

//關閉socket socketSend.Close(); //終止線程 threadReceive.Abort();