我想通过 udp 套接字发送和接收数据(unicode utf-8 字符串,DatagramSocket
。我一直在寻找答案,但只能找到使用InputStream
和类似的 TCP 传输的解决方案。
UDP有类似的方法吗?
UDP客户端
package testsocket;
import java.io.IOException;
import java.net.*;
public class TestSocketSender {
private DatagramSocket sock;
public static void main(String[] args) {
new TestSocketSender();
}
public TestSocketSender(){
try {
sock = new DatagramSocket();//, Inet4Address.getLocalHost());
sendData("Hello World\u00A9");
} catch (SocketException ex) {
ex.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
private void sendData(String data) throws IOException{
DatagramPacket datagram = new DatagramPacket(data.getBytes("utf-8"), data.length(), InetAddress.getLocalHost(), 5060);
sock.send(datagram);
}
}
UDP 服务器
package testsocket;
import java.io.IOException;
import java.net.*;
public class TestSocketListerner {
private DatagramSocket sock;
public static void main(String[] args) {
new TestSocketListerner();
}
public TestSocketListerner(){
try {
sock = new DatagramSocket(5060);//, Inet4Address.getLocalHost());
while(true){
System.out.println(recvData());
}
} catch (SocketException ex) {
ex.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}
private String recvData() throws IOException{
byte[] data = new byte[100];
DatagramPacket datagram = new DatagramPacket(data , data.length);
sock.receive(datagram);
return new String(datagram.getData(),datagram.getOffset(),datagram.getLength(),"utf-8");
}
}