應用C#完成基於TCP和UDP協定的收集通訊法式的根本示例。本站提示廣大學習愛好者:(應用C#完成基於TCP和UDP協定的收集通訊法式的根本示例)文章只能為提供參考,不一定能成為您想要的結果。以下是應用C#完成基於TCP和UDP協定的收集通訊法式的根本示例正文
C#中應用TCP通訊
TCP通訊須要通訊兩邊都在線,所以須要先啟動辦事端停止監聽,客戶端能力取得銜接,辦事端代碼:
static void Main(string[] args)
{
TcpClient client = null;
NetworkStream stream = null;
byte[] buffer = null;
string receiveString = null;
IPAddress localIP = IPAddress.Parse("127.0.0.1");
int localPort = 11000;
TcpListener listener = new TcpListener(localIP, localPort);//用當地IP和端話柄例化Listener
listener.Start();//開端監聽
while (true)
{
client = listener.AcceptTcpClient();//接收一個Client
buffer = new byte[client.ReceiveBufferSize];
stream = client.GetStream();//獲得收集流
stream.Read(buffer, 0, buffer.Length);//讀取收集流中的數據
stream.Close();//封閉流
client.Close();//封閉Client
receiveString = Encoding.Default.GetString(buffer).Trim('\0');//轉換成字符串
Console.WriteLine(receiveString);
}
}
只要辦事端開啟監聽後,客戶端能力准確銜接,所以辦事端要一向開啟監聽,客戶端每次發送數據,都要起首與辦事端樹立銜接,銜接樹立完成後才停止數據發送。客戶端代碼:
static void Main(string[] args)
{
string sendString = null;//要發送的字符串
byte[] sendData = null;//要發送的字節數組
TcpClient client = null;//TcpClient實例
NetworkStream stream = null;//收集流
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");//長途主機IP
int remotePort = 11000;//長途主機端口
while (true)//逝世輪回
{
sendString = Console.ReadLine();//獲得要發送的字符串
sendData = Encoding.Default.GetBytes(sendString);//獲得要發送的字節數組
client = new TcpClient();//實例化TcpClient
try
{
client.Connect(remoteIP, remotePort);//銜接長途主機
}
catch (System.Exception ex)
{
Console.WriteLine("銜接超時,辦事器沒有呼應!");//銜接掉敗
Console.ReadKey();
return;
}
stream = client.GetStream();//獲得收集流
stream.Write(sendData, 0, sendData.Length);//將數據寫入收集流
stream.Close();//封閉收集流
client.Close();//封閉客戶端
}
}

C#中應用UDP通訊
UDP通訊是無銜接通訊,客戶端在發送數據前無需與辦事器端樹立銜接,即便辦事器端不在線也能夠發送,然則不克不及包管辦事器端可以收到數據。
辦事器端代碼:
static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
//實例化一個長途端點,IP和端口可以隨便指定,等挪用client.Receive(ref remotePoint)時會將該端點改成真正發送端端點
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
client = new UdpClient(11000);
receiveData = client.Receive(ref remotePoint);//吸收數據
receiveString = Encoding.Default.GetString(receiveData);
Console.WriteLine(receiveString);
client.Close();//封閉銜接
}
}
客戶端代碼:
static void Main(string[] args)
{
string sendString = null;//要發送的字符串
byte[] sendData = null;//要發送的字節數組
UdpClient client = null;
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
int remotePort = 11000;
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//實例化一個長途端點
while (true)
{
sendString = Console.ReadLine();
sendData = Encoding.Default.GetBytes(sendString);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//將數據發送到長途端點
client.Close();//封閉銜接
}
}
