C# Socket類相關(guān)知識的學(xué)習(xí)
C# Socket 類為網(wǎng)絡(luò)通信提供了一套豐富的方法和屬性。Socket 類允許您使用 ProtocolType 枚舉中所列出的任何一種協(xié)議執(zhí)行異步和同步數(shù)據(jù)傳輸。Socket 類遵循異步方法的 .NET Framework 命名模式;例如,同步 Receive 方法對應(yīng)于異步 BeginReceive 和 EndReceive 方法。
如果應(yīng)用程序在執(zhí)行期間只需要一個線程,請使用下面的方法,這些方法適用于同步操作模式。
如果當(dāng)前使用的是面向連接的協(xié)議(如 TCP),則服務(wù)器可以使用 Listen 方法偵聽連接。Accept 方法處理任何傳入的連接請求,并返回可用于與遠(yuǎn)程主機(jī)進(jìn)行數(shù)據(jù)通信的 Socket??梢允褂么朔祷氐?Socket 來調(diào)用 Send 或 Receive 方法。如果要指定本地 IP 地址和端口號,請在調(diào)用 Listen 方法之前先調(diào)用 Bind 方法。如果您希望基礎(chǔ)服務(wù)提供程序?yàn)槟峙淇捎枚丝?,請使用端口?0。如果希望連接到偵聽主機(jī),請調(diào)用 Connect 方法。若要進(jìn)行數(shù)據(jù)通信,請調(diào)用 Send 或 Receive 方法。
如果當(dāng)前使用的是無連接協(xié)議(如 UDP),則根本不需要偵聽連接。調(diào)用 ReceiveFrom 方法可接受任何傳入的數(shù)據(jù)報。使用 SendTo 方法可將數(shù)據(jù)報發(fā)送到遠(yuǎn)程主機(jī)。
若要在執(zhí)行過程中使用單獨(dú)的線程處理通信,請使用下面的方法,這些方法適用于異步操作模式。
如果當(dāng)前使用的是面向連接的協(xié)議(如 TCP),則可使用 Socket、BeginConnect 和 EndConnect 方法來連接偵聽主機(jī)。通過使用 BeginSend 和 EndSend 方法,或者使用 BeginReceive 和 EndReceive 方法,可以進(jìn)行異步數(shù)據(jù)通信??梢允褂?BeginAccept 和 EndAccept 處理傳入的連接請求。
如果您使用的是 UDP 等無連接協(xié)議,則可以使用 BeginSendTo 和 EndSendTo 來發(fā)送數(shù)據(jù)報,而使用 BeginReceiveFrom 和 EndReceiveFrom 來接收數(shù)據(jù)報。
如果對一個套接字執(zhí)行多個異步操作,它們不一定按啟動時的順序完成。
當(dāng)數(shù)據(jù)發(fā)送和數(shù)據(jù)接收完成之后,可使用 Shutdown 方法來禁用 Socket。在調(diào)用 Shutdown 之后,可調(diào)用 Close 方法來釋放與 Socket 關(guān)聯(lián)的所有資源。
通過C# Socket 類,您可以使用 SetSocketOption 方法來配置 Socket??梢允褂?GetSocketOption 方法來檢索這些設(shè)置。
注意
如果要編寫相對簡單的應(yīng)用程序,而且不需要最高的性能,則可以考慮使用 TcpClient、TcpListener 和 UdpClient。這些類為 Socket 通信提供了更簡單、對用戶更友好的接口。
Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE 平臺說明: 并非所有設(shè)備的操作系統(tǒng)會支持全部的套接字選項(xiàng)。
服務(wù)器端代碼:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.Threading;
- using System.Net;
- using System.Net.Sockets;
- namespace ChatToolServer
- {
- public partial class Form1 : Form
- {
- //server-用于處理客戶端連接請求的socket
- Socket clientSocket = null;
- delegate void del();
- public Form1()
- {
- InitializeComponent();
- }
- //server-偵聽方法
- private void listen()
- {
- //獲取服務(wù)器IP
- string hostName = Dns.GetHostName();
- IPAddress[] ip = Dns.GetHostAddresses(hostName);
- IPAddress HostIp = ip[0];
- //創(chuàng)建一個網(wǎng)絡(luò)端點(diǎn)
- IPEndPoint iep = new IPEndPoint(HostIp, 82);
- //創(chuàng)建服務(wù)端服務(wù)端套接字
- Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //將套接字與網(wǎng)絡(luò)端點(diǎn)綁定
- serverSocket.Bind(iep);
- //將套接字置為偵聽狀態(tài),并設(shè)置最大隊(duì)列數(shù)為10
- serverSocket.Listen(10);
- //以同步方式從偵聽套接字的連接請求隊(duì)列中提取第一個掛起的連接請求,然后創(chuàng)建并返回新的 Socket
- //新的套接字:包含對方計算機(jī)的IP和端口號,可使用這個套接字與本機(jī)進(jìn)行通信
- clientSocket = serverSocket.Accept();
- if (clientSocket != null)
- {
- MessageBox.Show(”連接成功!”);
- }
- }
- private void send_Click(object sender, EventArgs e)
- {
- if (this.textBox1.Text != “”)//不能發(fā)送空消息
- {
- try
- {
- //發(fā)送數(shù)據(jù)
- string message = textBox1.Text;
- byte[] sendbytes = System.Text.Encoding.UTF8.GetBytes(message);
- int successSendBtyes = clientSocket.Send(sendbytes, sendbytes.Length, SocketFlags.None);
- }
- catch (Exception exp)
- {
- MessageBox.Show(exp.Message);
- }
- //將發(fā)送的數(shù)據(jù)顯示到對話窗口并使對話窗口的滾動條一直停留在最下方
- this.textBox2.Text +=”服務(wù)器:”+”\r\n” +textBox1.Text + “\r\n”;//發(fā)完一條消息就換行顯示
- this.textBox2.SelectionStart = this.textBox2.Text.Length;
- this.textBox2.ScrollToCaret();
- this.textBox1.Text = “”;//將發(fā)送窗口清空
- }
- else
- {
- MessageBox.Show(”發(fā)送內(nèi)容不能為空”);
- }
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- //server-創(chuàng)建并運(yùn)行偵聽線程
- Thread threadListen = new Thread(new ThreadStart(listen));
- threadListen.Start();
- }
- private void timer1_Tick(object sender, EventArgs e)
- {
- byte[] receiveBytes = new byte[1024];
- //如果偵聽后取得客戶端連接,并且客戶端的緩沖區(qū)中有內(nèi)容可讀,開始接收數(shù)據(jù)
- if (clientSocket != null)
- {
- if (clientSocket.Poll(100, SelectMode.SelectRead))
- {
- int successReceiveBytes = clientSocket.Receive(receiveBytes);
- this.textBox2.Text += “客戶端:” +”(”+ clientSocket.RemoteEndPoint.ToString()+”)”+”\r\n” +
- System.Text.Encoding.UTF8.GetString(receiveBytes, 0, successReceiveBytes) + “\r\n”;
- this.textBox2.SelectionStart = this.textBox2.Text.Length;//使對話窗口的滾動條一直停留在最下方
- this.textBox2.ScrollToCaret();
- }
- }
- }
- }
- }
客戶端代碼;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- namespace ChatToolClient
- {
- public partial class Form1 : Form
- {
- Socket clientSocket = null;//客戶端套接字
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- try
- {
- //建立與服務(wù)器連接的套接字
- IPAddress ip = IPAddress.Parse(”172.16.94.134″);
- IPEndPoint iep = new IPEndPoint(ip, 82);
- clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- clientSocket.Connect(iep);
- textBox2.Text = “連接成功” + “\r\n”;
- }
- catch (Exception exp)
- {
- MessageBox.Show(exp.Message);
- }
- }
- private void send_Click(object sender, EventArgs e)
- {
- if (textBox1.Text != “”)
- {
- try
- {
- //發(fā)送數(shù)據(jù)
- string message = textBox1.Text;
- byte[] sendbytes = System.Text.Encoding.UTF8.GetBytes(message);
- int successSendBtyes = clientSocket.Send(sendbytes, sendbytes.Length, SocketFlags.None);
- }
- catch (Exception exp)
- {
- MessageBox.Show(exp.Message);
- }
- //將發(fā)送的數(shù)據(jù)顯示到對話窗口并使對話窗口的滾動條一直停留在最下方
- this.textBox2.Text += “我自己:”+”\r\n”+textBox1.Text + “\r\n”;//發(fā)完一條消自己息就換行顯示
- this.textBox2.SelectionStart = this.textBox2.Text.Length;
- this.textBox2.ScrollToCaret();
- this.textBox1.Text = “”;//將發(fā)送窗口清空
- }
- else
- {
- MessageBox.Show(”發(fā)送內(nèi)容不能為空”);
- }
- }
- private void timer1_Tick(object sender, EventArgs e)
- {
- byte[] receiveBytes = new byte[1024];
- if (clientSocket.Poll(100, SelectMode.SelectRead))
- {
- int successReceiveBytes = clientSocket.Receive(receiveBytes);
- this.textBox2.Text +=”服務(wù)器:”+”\r\n”+
- System.Text.Encoding.UTF8.GetString(receiveBytes, 0, successReceiveBytes) + “\r\n”;
- this.textBox2.SelectionStart = this.textBox2.Text.Length;//使對話窗口的滾動條一直停留在最下方
- this.textBox2.ScrollToCaret();
- }
- }
- }
- }
C# Socket類方面的知識就介紹到這里,希望對大家有所幫助。
【編輯推薦】