c#--.net網路通訊學習1
一、服務端程式碼
1、建立服務端socket
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2、將ipv4地址轉換為ipAddress物件,有兩種方法:
第一種:IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 43, 163 });
第二種:IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
3、將ip地址和埠號轉換為IPEndPoint物件
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8088);
4、將ipEndPoint繫結到服務端Socket上
serverSocket.Bind(ipEndPoint);
5、進行監聽,10表示等待佇列中最多容納10個 請求
serverSocket.Listen(10);
6、進行接收,接收分為兩種:同步接收和非同步接收
第一種:同步接收(程式執行到這步阻塞)
Socket clientSocket = serverSocket.Accept();
第二種:非同步接收(程式不會阻塞)
serverSocket.BeginAccept(AcceptCallBack,serverSocket); //這個函式將serverSocet作為物件傳遞給過去
AcceptCallBack()是一個函式,注意,這個函式必須將IAsyncResult型別的變數作為引數,否則BeginAccept會報錯
static void AcceptCallBack(IAsyncResult ar)
{
Socket serverSocket = ar.AsyncState as Socket; //ar.AsyncState表示ar接收到的socket
Socket clientSocket = serverSocket.EndAccept(ar);
string msg = "hello,你好\n";
byte[] data = System.Text.Encoding.UTF8.GetBytes(msg);
clientSocket.Send(data);
clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);
serverSocket.BeginAccept(AcceptCallBack, serverSocket); //呼叫自身,繼續接受其他請求
}
static void ReceiveCallBack(IAsyncResult ar)
{
Socket clientSocket = null;
try
{
clientSocket = ar.AsyncState as Socket; //通過ar.AsyncState獲取到Socket
int count = clientSocket.EndReceive(ar); //count表示接收了多少位元組
if(count == 0) //客戶端關閉連線時服務端會無線迴圈收到0長度的位元組,因此當收到0長度的位元組時,關閉連線
{
clientSocket.Close();
return;
}
string msg = Encoding.UTF8.GetString(dataBuffer, 0, count);
Console.WriteLine("從客戶端接收到資料:" + msg);
clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket); //迴圈回撥
}
catch(Exception e)
{
Console.WriteLine(e);
if (clientSocket != null)
clientSocket.Close();
}
finally
{
}
}