溫馨提示×

C#如何實現(xiàn)Socket數(shù)據(jù)接收

c#
小億
271
2023-07-31 13:00:01
欄目: 編程語言

在C#中實現(xiàn)Socket數(shù)據(jù)接收,可以使用System.Net.Sockets命名空間中的Socket類。以下是一個示例代碼:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SocketReceiver
{
private const int BUFFER_SIZE = 1024;
public static void Main()
{
StartListening();
}
private static void StartListening()
{
// 創(chuàng)建Socket對象
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 綁定IP地址和端口
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8888);
listener.Bind(localEndPoint);
// 開始監(jiān)聽
listener.Listen(10);
Console.WriteLine("等待客戶端連接...");
while (true)
{
// 接收連接請求
Socket handler = listener.Accept();
Console.WriteLine("客戶端已連接");
byte[] buffer = new byte[BUFFER_SIZE];
string data = null;
while (true)
{
// 接收數(shù)據(jù)
int bytesRead = handler.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, bytesRead);
// 判斷數(shù)據(jù)是否接收完畢
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("接收到的數(shù)據(jù):" + data);
// 關(guān)閉連接
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
}

上述代碼創(chuàng)建了一個Socket對象,綁定了本地IP地址和端口,并開始監(jiān)聽連接請求。當(dāng)有客戶端連接成功后,進(jìn)入數(shù)據(jù)接收循環(huán),通過Receive方法接收數(shù)據(jù),直到接收到結(jié)束標(biāo)記""為止。最后關(guān)閉連接。

注意:上述代碼僅實現(xiàn)了單次數(shù)據(jù)接收,如果需要持續(xù)接收數(shù)據(jù),可以將數(shù)據(jù)處理部分移至循環(huán)外部,并修改循環(huán)控制條件。

0