C#Socket通訊基礎(非同步Socket通訊TCP)伺服器與客戶端
阿新 • • 發佈:2018-11-07
一、效果圖
二、伺服器端程式碼(原始碼下載地址:https://download.csdn.net/download/xiaochenxihua/10748789)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Test_AsynSocketTcp { public partial class Server : Form { public Server() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } //開始監聽 private void button1_Click(object sender, EventArgs e) { //ip地址 IPAddress ip = IPAddress.Parse(txtIP.Text); // IPAddress ip = IPAddress.Any; //埠號 IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text)); //建立監聽用的Socket /* * AddressFamily.InterNetWork:使用 IP4地址。 SocketType.Stream:支援可靠、雙向、基於連線的位元組流,而不重複資料。此型別的 Socket 與單個對方主機進行通訊,並且在通訊開始之前需要遠端主機連線。Stream 使用傳輸控制協議 (Tcp) ProtocolType 和 InterNetworkAddressFamily。 ProtocolType.Tcp:使用傳輸控制協議。 */ //使用IPv4地址,流式socket方式,tcp協議傳遞資料 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立好socket後,必須告訴socket繫結的IP地址和埠號。 //讓socket監聽point try { //socket監聽哪個埠 socket.Bind(point); //同一個時間點過來10個客戶端,排隊 socket.Listen(10); ShowMsg("伺服器開始監聽"); Thread thread = new Thread(AcceptInfo); thread.IsBackground = true; thread.Start(socket); } catch (Exception ex) { ShowMsg(ex.Message); } } //記錄通訊用的Socket Dictionary<string, Socket> dic = new Dictionary<string, Socket>(); // private Socket client; private void AcceptInfo(object o) { Socket socket = o as Socket; while (true) { //通訊用socket try { //建立通訊用的Socket Socket tSocket = socket.Accept(); string point = tSocket.RemoteEndPoint.ToString(); //IPEndPoint endPoint = (IPEndPoint)client.RemoteEndPoint; //string me = Dns.GetHostName();//得到本機名稱 //MessageBox.Show(me); ShowMsg(point + "連線成功!"); cboIpPort.Items.Add(point); dic.Add(point, tSocket); //接收訊息 Thread th = new Thread(ReceiveMsg); th.IsBackground = true; th.Start(tSocket); } catch (Exception ex) { ShowMsg(ex.Message); break; } } } //接收訊息 void ReceiveMsg(object o) { Socket client = o as Socket; while (true) { //接收客戶端傳送過來的資料 try { //定義byte陣列存放從客戶端接收過來的資料 byte[] buffer = new byte[1024 * 1024]; //將接收過來的資料放到buffer中,並返回實際接受資料的長度 int n = client.Receive(buffer); //將位元組轉換成字串 string words = Encoding.UTF8.GetString(buffer, 0, n); ShowMsg(client.RemoteEndPoint.ToString() + ":" + words); } catch (Exception ex) { ShowMsg(ex.Message); break; } } } void ShowMsg(string msg) { txtLog.AppendText(msg + "\r\n"); } //給客戶端傳送訊息 private void button2_Click(object sender, EventArgs e) { try { ShowMsg(txtMsg.Text); string ip = cboIpPort.Text; byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text); dic[ip].Send(buffer); // client.Send(buffer); } catch (Exception ex) { ShowMsg(ex.Message); } } }//Class_end }
三、客戶端程式碼(原始碼下載地址:https://download.csdn.net/download/xiaochenxihua/10748794)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Test_AsynSocketTcpClient { public partial class Client : Form { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public Client() { InitializeComponent(); } private void btnConnection_Click(object sender, EventArgs e) { //連線到的目標IP IPAddress ip = IPAddress.Parse(txtIP.Text); //IPAddress ip = IPAddress.Any; //連線到目標IP的哪個應用(埠號!) IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text)); try { //連線到伺服器 client.Connect(point); ShowMsg("連線成功"); ShowMsg("伺服器" + client.RemoteEndPoint.ToString()); ShowMsg("客戶端:" + client.LocalEndPoint.ToString()); //連線成功後,就可以接收伺服器傳送的資訊了 Thread th = new Thread(ReceiveMsg); th.IsBackground = true; th.Start(); } catch (Exception ex) { ShowMsg(ex.Message); } } //接收伺服器的訊息 private void ReceiveMsg() { while (true) { try { byte[] buffer = new byte[1024 * 1024]; int n = client.Receive(buffer); string s = Encoding.UTF8.GetString(buffer, 0, n); ShowMsg(client.RemoteEndPoint.ToString() + ":" + s); } catch (Exception ex) { ShowMsg(ex.Message); break; } } } /// <summary> /// 展示訊息 /// </summary> /// <param name="msg"></param> void ShowMsg(string msg) { txtInfo.AppendText(msg + "\r\n"); } private void btnSend_Click(object sender, EventArgs e) { //客戶端給伺服器發訊息 if (client != null) { try { ShowMsg(txtMsg.Text); byte[] buffer = Encoding.UTF8.GetBytes(txtMsg.Text); client.Send(buffer); } catch (Exception ex) { ShowMsg(ex.Message); } } } private void Client_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } }//class_end }
注意:該內容來自:http://www.cnblogs.com/weilengdeyu/archive/2013/03/08/2949101.html
擴充套件網址:https://www.cnblogs.com/dotnet261010/p/6211900.html
https://blog.csdn.net/qq_32623363/article/details/72887920