標籤:style http java color 使用 資料
UDP通訊是無串連通訊,用戶端在發送資料前無需與伺服器端建立串連,即使伺服器端不線上也可以發送,但是不能保證伺服器端可以收到資料。
伺服器端代碼:
C#代碼
- 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();//關閉串連
- }
- }
用戶端代碼:
C#代碼
- 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();//關閉串連
- }
- }