1. 程式人生 > 其它 >java中請給出UDP的DatagramSocket通訊的例子?

java中請給出UDP的DatagramSocket通訊的例子?

java中請給出UDP的DatagramSocket通訊的例子?

3.UDP(資料報)協議的通訊例項

馬克-to-win:在UDP程式設計當中,技術上沒有一個伺服器和客戶端的概念,即沒有類似於TCP中的ServerSocket類,只有主動和被動之說, 客戶端和伺服器都用DatagramSocket(MyPORT)來繫結到一個埠,傳送和接收dataPacket,它們是對等的雙方。不過通常來講, 先發送資料的被認為是客戶端。in UDP, there is no concept of server or client, only active and passive, client and server both use new DatagramSocket(MyPORT) to bind to a port to use the port to send and receive the dataPacket, the counterpart which initially send the dataPacket is deemed as the client. unlike the TCP protocol, there, there is really ServerSocket.
UDP通訊主要有兩個類,DatagramPacket是資料容器,它攜帶自己來自何處,以及打算去哪裡的資訊。DatagramSocket用來發送或接收DatagramPacket。

DatagramPacket不僅需要包含正式的資料,也要包含網路地址以及埠號,以決定它的目的地。



例:2.3.1(客戶端寫,伺服器端讀)

伺服器端:

import java.net.*;
import java.io.*;
import java.util.*;
public class TestMark_to_win {
static final int MyPORT = 1711;
public static void main(String[] args) throws IOException {
byte[] bufreceive = new byte[1000];
DatagramPacket packetreceive = new DatagramPacket(bufreceive,
bufreceive.length);//測試結果bufreceive.length是1000
DatagramSocket socket;
socket = new DatagramSocket(MyPORT);
// Block until a datagram appears:
socket.receive(packetreceive);
String stringreceive = new String(packetreceive.getData(), 0,
packetreceive.getLength());
System.out.println(stringreceive);
socket.close();
}
}

客戶端程式:
import java.net.*;
import java.io.*;
import java.util.*;
public class Test {
static final int MyPORT = 1710;
static final int SERVERPORT = 1711;
public static void main(String[] args) throws IOException {
byte[] bufsend = new byte[1000];
DatagramSocket client;
InetAddress destination = InetAddress.getByName("localhost");
client = new DatagramSocket(MyPORT);
bufsend = "java study".getBytes();// string encode to a byte array
DatagramPacket sendpacket = new DatagramPacket(bufsend, bufsend.length,
destination, SERVERPORT);
client.send(sendpacket);
client.close();
}
}

更多內容請見原文,文章轉載自:

https://blog.csdn.net/qq_44639795/article/details/102079039