Socket通訊實例(C#)

SOCKET原理服務器


1、套接字(socket)概念網絡


  套接字(socket)是通訊的基石,是支持TCP/IP協議的網絡通訊的基本操做單元。它是網絡通訊過程當中端點的抽象表示,包含進行網絡通訊必須的五種信息:鏈接使用的協議,本地主機的IP地址,本地進程的協議端口,遠地主機的IP地址,遠地進程的協議端口。

  應用層經過傳輸層進行數據通訊時,TCP會遇到同時爲多個應用程序進程提供併發服務的問題。多個TCP鏈接或多個應用程序進程可能須要經過同一個 TCP協議端口傳輸數據。爲了區別不一樣的應用程序進程和鏈接,許多計算機操做系統爲應用程序與TCP/IP協議交互提供了套接字(Socket)接口。應 用層能夠和傳輸層經過Socket接口,區分來自不一樣應用程序進程或網絡鏈接的通訊,實現數據傳輸的併發服務。

2、創建socket鏈接併發


  創建Socket鏈接至少須要一對套接字,其中一個運行於客戶端,稱爲ClientSocket ,另外一個運行於服務器端,稱爲ServerSocket 。

  套接字之間的鏈接過程分爲三個步驟:服務器監聽,客戶端請求,鏈接確認。socket

  1. 服務器監聽:服務器端套接字並不定位具體的客戶端套接字,而是處於等待鏈接的狀態,實時監控網絡狀態,等待客戶端的鏈接請求 
  2. 客戶端請求:指客戶端的套接字提出鏈接請求,要鏈接的目標是服務器端的套接字。爲此,客戶端的套接字必須首先描述它要鏈接的服務器的套接字,指出服務器端套接字的地址和端口號,而後就向服務器端套接字提出鏈接請求。
  3. 鏈接確認:當服務器端套接字監聽到或者說接收到客戶端套接字的鏈接請求時,就響應客戶端套接字的請求,創建一個新的線程,把服務器端套接字的描述發給客戶 端,一旦客戶端確認了此描述,雙方就正式創建鏈接。而服務器端套接字繼續處於監聽狀態,繼續接收其餘客戶端套接字的鏈接請求。

3、SOCKET鏈接與TCP鏈接編輯器


  建立Socket鏈接時,能夠指定使用的傳輸層協議,Socket能夠支持不一樣的傳輸層協議(TCP或UDP),當使用TCP協議進行鏈接時,該Socket鏈接就是一個TCP鏈接。ide

4、Socket鏈接與HTTP鏈接 

  因爲一般狀況下Socket鏈接就是TCP鏈接,所以Socket鏈接一旦創建,通訊雙方便可開始相互發送數據內容,直到雙方鏈接斷開。但在實際網絡應用 中,客戶端到服務器之間的通訊每每須要穿越多箇中間節點,例如路由器、網關、防火牆等,大部分防火牆默認會關閉長時間處於非活躍狀態的鏈接而致使 Socket 鏈接斷連,所以須要經過輪詢告訴網絡,該鏈接處於活躍狀態。

  而HTTP鏈接使用的是「請求—響應」的方式,不只在請求時須要先創建鏈接,並且須要客戶端向服務器發出請求後,服務器端才能回覆數據。

  不少狀況下,須要服務器端主動向客戶端推送數據,保持客戶端與服務器數據的實時與同步。此時若雙方創建的是Socket鏈接,服務器就能夠直接將數據傳送 給客戶端;若雙方創建的是HTTP鏈接,則服務器須要等到客戶端發送一次請求後才能將數據傳回給客戶端,所以,客戶端定時向服務器端發送鏈接請求,不只可 以保持在線,同時也是在「詢問」服務器是否有新的數據,若是有就將數據傳給客戶端。this

5、Socket服務端與客戶端通訊示意圖spa

6、服務端與客戶端代碼操作系統

  一、服務端線程

  (1)服務端窗口設計

  1 namespace SocketForm
  2 {
  3     partial class Form1
  4     {
  5         /// <summary>
  6         /// 必需的設計器變量。
  7         /// </summary>
  8         private System.ComponentModel.IContainer components = null;
  9 
 10         /// <summary>
 11         /// 清理全部正在使用的資源。
 12         /// </summary>
 13         /// <param name="disposing">若是應釋放託管資源,爲 true;不然爲 false。</param>
 14         protected override void Dispose(bool disposing)
 15         {
 16             if (disposing && (components != null))
 17             {
 18                 components.Dispose();
 19             }
 20             base.Dispose(disposing);
 21         }
 22 
 23         #region Windows 窗體設計器生成的代碼
 24 
 25         /// <summary>
 26         /// 設計器支持所需的方法 - 不要
 27         /// 使用代碼編輯器修改此方法的內容。
 28         /// </summary>
 29         private void InitializeComponent()
 30         {
 31             this.panel1 = new System.Windows.Forms.Panel();
 32             this.tb_ip = new System.Windows.Forms.TextBox();
 33             this.lb_Ip = new System.Windows.Forms.Label();
 34             this.lb_port = new System.Windows.Forms.Label();
 35             this.tb_port = new System.Windows.Forms.TextBox();
 36             this.bt_connnect = new System.Windows.Forms.Button();
 37             this.listBox1 = new System.Windows.Forms.ListBox();
 38             this.txt_msg = new System.Windows.Forms.TextBox();
 39             this.bt_send = new System.Windows.Forms.Button();
 40             this.panel1.SuspendLayout();
 41             this.SuspendLayout();
 42             // 
 43             // panel1
 44             // 
 45             this.panel1.Controls.Add(this.bt_connnect);
 46             this.panel1.Controls.Add(this.lb_port);
 47             this.panel1.Controls.Add(this.tb_port);
 48             this.panel1.Controls.Add(this.lb_Ip);
 49             this.panel1.Controls.Add(this.tb_ip);
 50             this.panel1.Location = new System.Drawing.Point(21, 12);
 51             this.panel1.Name = "panel1";
 52             this.panel1.Size = new System.Drawing.Size(580, 70);
 53             this.panel1.TabIndex = 0;
 54             // 
 55             // tb_ip
 56             // 
 57             this.tb_ip.Location = new System.Drawing.Point(44, 18);
 58             this.tb_ip.Name = "tb_ip";
 59             this.tb_ip.Size = new System.Drawing.Size(100, 21);
 60             this.tb_ip.TabIndex = 0;
 61             this.tb_ip.Text = "127.0.0.1";
 62             // 
 63             // lb_Ip
 64             // 
 65             this.lb_Ip.AutoSize = true;
 66             this.lb_Ip.Location = new System.Drawing.Point(15, 21);
 67             this.lb_Ip.Name = "lb_Ip";
 68             this.lb_Ip.Size = new System.Drawing.Size(23, 12);
 69             this.lb_Ip.TabIndex = 1;
 70             this.lb_Ip.Text = "IP:";
 71             // 
 72             // lb_port
 73             // 
 74             this.lb_port.AutoSize = true;
 75             this.lb_port.Location = new System.Drawing.Point(158, 24);
 76             this.lb_port.Name = "lb_port";
 77             this.lb_port.Size = new System.Drawing.Size(35, 12);
 78             this.lb_port.TabIndex = 3;
 79             this.lb_port.Text = "Port:";
 80             // 
 81             // tb_port
 82             // 
 83             this.tb_port.Location = new System.Drawing.Point(199, 21);
 84             this.tb_port.Name = "tb_port";
 85             this.tb_port.Size = new System.Drawing.Size(100, 21);
 86             this.tb_port.TabIndex = 2;
 87             this.tb_port.Text = "80";
 88             // 
 89             // bt_connnect
 90             // 
 91             this.bt_connnect.Location = new System.Drawing.Point(316, 15);
 92             this.bt_connnect.Name = "bt_connnect";
 93             this.bt_connnect.Size = new System.Drawing.Size(132, 42);
 94             this.bt_connnect.TabIndex = 4;
 95             this.bt_connnect.Text = "開始監聽";
 96             this.bt_connnect.UseVisualStyleBackColor = true;
 97             this.bt_connnect.Click += new System.EventHandler(this.bt_connnect_Click);
 98             // 
 99             // listBox1
100             // 
101             this.listBox1.FormattingEnabled = true;
102             this.listBox1.ItemHeight = 12;
103             this.listBox1.Location = new System.Drawing.Point(21, 112);
104             this.listBox1.Name = "listBox1";
105             this.listBox1.Size = new System.Drawing.Size(580, 124);
106             this.listBox1.TabIndex = 1;
107             // 
108             // txt_msg
109             // 
110             this.txt_msg.Location = new System.Drawing.Point(21, 255);
111             this.txt_msg.Multiline = true;
112             this.txt_msg.Name = "txt_msg";
113             this.txt_msg.Size = new System.Drawing.Size(424, 73);
114             this.txt_msg.TabIndex = 2;
115             // 
116             // bt_send
117             // 
118             this.bt_send.Location = new System.Drawing.Point(471, 266);
119             this.bt_send.Name = "bt_send";
120             this.bt_send.Size = new System.Drawing.Size(119, 52);
121             this.bt_send.TabIndex = 3;
122             this.bt_send.Text = "發送";
123             this.bt_send.UseVisualStyleBackColor = true;
124             this.bt_send.Click += new System.EventHandler(this.bt_send_Click);
125             // 
126             // Form1
127             // 
128             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
129             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
130             this.ClientSize = new System.Drawing.Size(695, 340);
131             this.Controls.Add(this.bt_send);
132             this.Controls.Add(this.txt_msg);
133             this.Controls.Add(this.listBox1);
134             this.Controls.Add(this.panel1);
135             this.Name = "Form1";
136             this.Text = "SocketForm";
137             this.Load += new System.EventHandler(this.Form1_Load);
138             this.panel1.ResumeLayout(false);
139             this.panel1.PerformLayout();
140             this.ResumeLayout(false);
141             this.PerformLayout();
142 
143         }
144 
145         #endregion
146 
147         private System.Windows.Forms.Panel panel1;
148         private System.Windows.Forms.Button bt_connnect;
149         private System.Windows.Forms.Label lb_port;
150         private System.Windows.Forms.TextBox tb_port;
151         private System.Windows.Forms.Label lb_Ip;
152         private System.Windows.Forms.TextBox tb_ip;
153         private System.Windows.Forms.ListBox listBox1;
154         private System.Windows.Forms.TextBox txt_msg;
155         private System.Windows.Forms.Button bt_send;
156     }
157 }
View Code

  (2)服務端邏輯設計

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Net;
  8 using System.Net.Sockets;
  9 using System.Text;
 10 using System.Threading;
 11 using System.Windows.Forms;
 12 
 13 namespace SocketForm
 14 {
 15     public partial class Form1 : Form
 16     {
 17         public Form1()
 18         {
 19             InitializeComponent();
 20         }
 21 
 22         private void bt_connnect_Click(object sender, EventArgs e)
 23         {
 24 
 25             try
 26             {
 27                 //點擊開始監聽時 在服務端建立一個負責監聽IP和端口號的Socket
 28                 Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 29                 IPAddress ip = IPAddress.Any;
 30                 //建立對象端口
 31                 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(tb_port.Text));
 32 
 33                 socketWatch.Bind(point);//綁定端口號
 34                 ShowMsg("監聽成功!");
 35                 socketWatch.Listen(10);//設置監聽
 36 
 37                 //建立監聽線程
 38                 Thread thread = new Thread(Listen);
 39                 thread.IsBackground = true;
 40                 thread.Start(socketWatch);
 41             }
 42             catch { }
 43            
 44         }
 45        
 46         /// <summary>
 47         /// 等待客戶端的鏈接 而且建立與之通訊的Socket
 48         /// </summary>
 49         Socket socketSend;
 50         void Listen(object o)
 51         {
 52             try
 53             {
 54                 Socket socketWatch = o as Socket;
 55                 while (true)
 56                 {
 57                     socketSend = socketWatch.Accept();//等待接收客戶端鏈接
 58                     ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "鏈接成功!");
 59                     //開啓一個新線程,執行接收消息方法
 60                     Thread r_thread = new Thread(Received);
 61                     r_thread.IsBackground = true;
 62                     r_thread.Start(socketSend);
 63                 }
 64             }
 65             catch { }
 66         }
 67         /// <summary>
 68         /// 服務器端不停的接收客戶端發來的消息
 69         /// </summary>
 70         /// <param name="o"></param>
 71         void Received(object o)
 72         {
 73             try
 74             {
 75                 Socket socketSend = o as Socket;
 76                 while (true)
 77                 {
 78                     //客戶端鏈接服務器成功後,服務器接收客戶端發送的消息
 79                     byte[] buffer = new byte[1024 * 1024 * 3];
 80                     //實際接收到的有效字節數
 81                     int len = socketSend.Receive(buffer);
 82                     if (len == 0)
 83                     {
 84                         break;
 85                     }
 86                     string str = Encoding.UTF8.GetString(buffer, 0, len);
 87                     ShowMsg(socketSend.RemoteEndPoint + ":" + str);
 88                 }
 89             }
 90             catch { }
 91         }
 92         /// <summary>
 93         /// 服務器向客戶端發送消息
 94         /// </summary>
 95         /// <param name="str"></param>
 96         void Send(string str) {
 97             byte[] buffer = Encoding.UTF8.GetBytes(str);
 98             socketSend.Send(buffer);
 99         }
100 
101         void ShowMsg(string msg)
102         {
103             listBox1.Items.Add(msg + "\r\n");
104         }
105 
106         private void Form1_Load(object sender, EventArgs e)
107         {
108             Control.CheckForIllegalCrossThreadCalls = false;
109         }
110 
111         private void bt_send_Click(object sender, EventArgs e)
112         {
113             Send(txt_msg.Text.Trim());
114         }
115     }
116 }
View Code

  二、客戶端

  (1)客戶端窗口設計

  1 namespace SocketClient
  2 {
  3     partial class Form1
  4     {
  5         /// <summary>
  6         /// 必需的設計器變量。
  7         /// </summary>
  8         private System.ComponentModel.IContainer components = null;
  9 
 10         /// <summary>
 11         /// 清理全部正在使用的資源。
 12         /// </summary>
 13         /// <param name="disposing">若是應釋放託管資源,爲 true;不然爲 false。</param>
 14         protected override void Dispose(bool disposing)
 15         {
 16             if (disposing && (components != null))
 17             {
 18                 components.Dispose();
 19             }
 20             base.Dispose(disposing);
 21         }
 22 
 23         #region Windows 窗體設計器生成的代碼
 24 
 25         /// <summary>
 26         /// 設計器支持所需的方法 - 不要
 27         /// 使用代碼編輯器修改此方法的內容。
 28         /// </summary>
 29         private void InitializeComponent()
 30         {
 31             this.panel1 = new System.Windows.Forms.Panel();
 32             this.lb_ip = new System.Windows.Forms.Label();
 33             this.txt_ip = new System.Windows.Forms.TextBox();
 34             this.txt_port = new System.Windows.Forms.TextBox();
 35             this.lb_port = new System.Windows.Forms.Label();
 36             this.bt_connect = new System.Windows.Forms.Button();
 37             this.textBox1 = new System.Windows.Forms.TextBox();
 38             this.txt_msg = new System.Windows.Forms.TextBox();
 39             this.bt_send = new System.Windows.Forms.Button();
 40             this.panel1.SuspendLayout();
 41             this.SuspendLayout();
 42             // 
 43             // panel1
 44             // 
 45             this.panel1.Controls.Add(this.bt_connect);
 46             this.panel1.Controls.Add(this.txt_port);
 47             this.panel1.Controls.Add(this.lb_port);
 48             this.panel1.Controls.Add(this.txt_ip);
 49             this.panel1.Controls.Add(this.lb_ip);
 50             this.panel1.Location = new System.Drawing.Point(12, 12);
 51             this.panel1.Name = "panel1";
 52             this.panel1.Size = new System.Drawing.Size(463, 75);
 53             this.panel1.TabIndex = 0;
 54             // 
 55             // lb_ip
 56             // 
 57             this.lb_ip.AutoSize = true;
 58             this.lb_ip.Location = new System.Drawing.Point(14, 23);
 59             this.lb_ip.Name = "lb_ip";
 60             this.lb_ip.Size = new System.Drawing.Size(23, 12);
 61             this.lb_ip.TabIndex = 0;
 62             this.lb_ip.Text = "IP:";
 63             // 
 64             // txt_ip
 65             // 
 66             this.txt_ip.Location = new System.Drawing.Point(43, 20);
 67             this.txt_ip.Name = "txt_ip";
 68             this.txt_ip.Size = new System.Drawing.Size(100, 21);
 69             this.txt_ip.TabIndex = 1;
 70             this.txt_ip.Text = "127.0.0.1";
 71             // 
 72             // txt_port
 73             // 
 74             this.txt_port.Location = new System.Drawing.Point(207, 23);
 75             this.txt_port.Name = "txt_port";
 76             this.txt_port.Size = new System.Drawing.Size(100, 21);
 77             this.txt_port.TabIndex = 3;
 78             this.txt_port.Text = "2001";
 79             // 
 80             // lb_port
 81             // 
 82             this.lb_port.AutoSize = true;
 83             this.lb_port.Location = new System.Drawing.Point(166, 29);
 84             this.lb_port.Name = "lb_port";
 85             this.lb_port.Size = new System.Drawing.Size(35, 12);
 86             this.lb_port.TabIndex = 2;
 87             this.lb_port.Text = "port:";
 88             // 
 89             // bt_connect
 90             // 
 91             this.bt_connect.Location = new System.Drawing.Point(313, 9);
 92             this.bt_connect.Name = "bt_connect";
 93             this.bt_connect.Size = new System.Drawing.Size(113, 47);
 94             this.bt_connect.TabIndex = 4;
 95             this.bt_connect.Text = "鏈接";
 96             this.bt_connect.UseVisualStyleBackColor = true;
 97             this.bt_connect.Click += new System.EventHandler(this.bt_connect_Click);
 98             // 
 99             // textBox1
100             // 
101             this.textBox1.Location = new System.Drawing.Point(12, 103);
102             this.textBox1.Multiline = true;
103             this.textBox1.Name = "textBox1";
104             this.textBox1.Size = new System.Drawing.Size(463, 114);
105             this.textBox1.TabIndex = 1;
106             // 
107             // txt_msg
108             // 
109             this.txt_msg.Location = new System.Drawing.Point(12, 246);
110             this.txt_msg.Multiline = true;
111             this.txt_msg.Name = "txt_msg";
112             this.txt_msg.Size = new System.Drawing.Size(291, 54);
113             this.txt_msg.TabIndex = 2;
114             // 
115             // bt_send
116             // 
117             this.bt_send.Location = new System.Drawing.Point(325, 246);
118             this.bt_send.Name = "bt_send";
119             this.bt_send.Size = new System.Drawing.Size(113, 54);
120             this.bt_send.TabIndex = 3;
121             this.bt_send.Text = "發送";
122             this.bt_send.UseVisualStyleBackColor = true;
123             this.bt_send.Click += new System.EventHandler(this.bt_send_Click);
124             // 
125             // Form1
126             // 
127             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
128             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
129             this.ClientSize = new System.Drawing.Size(493, 323);
130             this.Controls.Add(this.bt_send);
131             this.Controls.Add(this.txt_msg);
132             this.Controls.Add(this.textBox1);
133             this.Controls.Add(this.panel1);
134             this.Name = "Form1";
135             this.Text = "Form1";
136             this.Load += new System.EventHandler(this.Form1_Load);
137             this.panel1.ResumeLayout(false);
138             this.panel1.PerformLayout();
139             this.ResumeLayout(false);
140             this.PerformLayout();
141 
142         }
143 
144         #endregion
145 
146         private System.Windows.Forms.Panel panel1;
147         private System.Windows.Forms.Label lb_ip;
148         private System.Windows.Forms.Button bt_connect;
149         private System.Windows.Forms.TextBox txt_port;
150         private System.Windows.Forms.Label lb_port;
151         private System.Windows.Forms.TextBox txt_ip;
152         private System.Windows.Forms.TextBox textBox1;
153         private System.Windows.Forms.TextBox txt_msg;
154         private System.Windows.Forms.Button bt_send;
155     }
156 }
View Code

  (2)客戶端邏輯設計

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Net;
 8 using System.Net.Sockets;
 9 using System.Text;
10 using System.Threading;
11 using System.Windows.Forms;
12 
13 namespace SocketClient
14 {
15     public partial class Form1 : Form
16     {
17         public Form1()
18         {
19             InitializeComponent();
20         }
21         Socket socketSend;
22         private void bt_connect_Click(object sender, EventArgs e)
23         {
24             try
25             {
26                 //建立客戶端Socket,得到遠程ip和端口號
27                 socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
28                 IPAddress ip = IPAddress.Parse(txt_ip.Text);
29                 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txt_port.Text));
30 
31                 socketSend.Connect(point);
32                 ShowMsg("鏈接成功!");
33                 //開啓新的線程,不停的接收服務器發來的消息
34                 Thread c_thread = new Thread(Received);
35                 c_thread.IsBackground = true;
36                 c_thread.Start();
37             }
38             catch (Exception){
39                 ShowMsg("IP或者端口號錯誤...");
40             }
41  
42         }
43         void ShowMsg(string str)
44         {
45             textBox1.AppendText(str + "\r\n");
46         }
47         /// <summary>
48         /// 接收服務端返回的消息
49         /// </summary>
50         void Received()
51         {
52             while (true)
53             {
54                 try
55                 {
56                     byte[] buffer = new byte[1024 * 1024 * 3];
57                     //實際接收到的有效字節數
58                     int len = socketSend.Receive(buffer);
59                     if (len == 0)
60                     {
61                         break;
62                     }
63                     string str = Encoding.UTF8.GetString(buffer, 0, len);
64                     ShowMsg(socketSend.RemoteEndPoint + ":" + str);
65                 }
66                 catch { }
67             }
68         } 
69         /// <summary>
70         /// 向服務器發送消息
71         /// </summary>
72         /// <param name="sender"></param>
73         /// <param name="e"></param>
74         private void bt_send_Click(object sender, EventArgs e)
75         {
76             try
77             {
78                 string msg = txt_msg.Text.Trim();
79                 byte[] buffer = new byte[1024 * 1024 * 3];
80                 buffer = Encoding.UTF8.GetBytes(msg);
81                 socketSend.Send(buffer);
82             }
83             catch { }
84         }
85 
86         private void Form1_Load(object sender, EventArgs e)
87         {
88             Control.CheckForIllegalCrossThreadCalls = false;
89         }
90     }
91 }
View Code

7、運行效果

  一、服務端

  二、客戶端

相關文章
相關標籤/搜索