2.Socket連接過程根據連接啓動的方式以及本地套接字要連接的目標,套接字之間的連接過程可以分爲三個步驟:服務器監聽,客戶端請求,連接確認。
(1)服務器監聽:是服務器端套接字並不定位具體的客戶端套接字,而是處於等待連
接的狀態,實時監控網絡狀態。
(2)客戶端請求:是指由客戶端的套接字提出連接請求,要連接的目標是服務器端的
套接字。爲此,客戶端的套接字必須首先描述它要連接的服務器的套接字,指出服務器
端套接字的地址和端口號,然後就向服務器端套接字提出連接請求。
(3)連接確認:是指當服務器端套接字監聽到或者說接收到客戶端套接字的連接請求,
它就響應客戶端套接字的請求,建立一個新的線程,把服務器端套接字的描述發給客戶
端,一旦客戶端確認了此描述,連接就建立好了。而服務器端套接字繼續處於監聽狀態,
繼續接收其他客戶端套接字的連接請求。
3.代碼示例:
(1)服務器端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
private static byte[] result = new byte[1024];//定義傳輸字節流的大小
private static int myProt = 8886;//定義端口
static Socket serSocket;//定義服務器端Socket
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");//獲取服務器端IP地址
serSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serSocket.Bind(new IPEndPoint(ip, myProt));//綁定IP地址:端口
serSocket.Listen(10);//設定最多10個排隊連接請求
Console.WriteLine("啓動監聽{0}成功", serSocket.LocalEndPoint.ToString());
Thread myThread = new Thread(Communication);//創建線程
myThread.Start();
Console.ReadLine();
}
private static void Communication()
{
while (true)
{
Socket cliSocket = serSocket.Accept();//建立一個與服務器端Socket一樣的客戶端Socket
cliSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));//客戶端發送請求
Thread reThrea = new Thread(ReceiveMessage);//新建線程
reThrea.Start(cliSocket);
}
}
private static void ReceiveMessage(object cliSocket)
{
Socket myCliSocket = (Socket)cliSocket;
while (true)
{
try
{
int receNumber = myCliSocket.Receive(result);
Console.WriteLine("接收客戶端{0}消息");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myCliSocket.Shutdown(SocketShutdown.Both);
myCliSocket.Close();
break;
}
}
}
}
}
(2)客戶端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket cliSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//創建Socket
try
{
cliSocket.Connect(new IPEndPoint(ip, 8886));//進行連接
Console.WriteLine("連接服務器成功");
}
catch
{
Console.WriteLine("連接服務器失敗,請按回車鍵退出!");
return;
}
int reLength = cliSocket.Receive(result);
Console.WriteLine("接收服務器消息");
for (int i = 0; i < 10; i++)
{
try
{
Thread.Sleep(1000);
string sendMessage = "client send Message Hellp" + DateTime.Now;
cliSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("向服務器發送消息:{0}" + sendMessage);
}
catch
{
cliSocket.Shutdown(SocketShutdown.Both);
cliSocket.Close();
break;
}
}
Console.WriteLine("發送完畢,按回車鍵退出");
Console.ReadLine();
}
}
}