我想通過發送和UDP套接字接收數據(Unicode的UTF-8字符串,DatagramSocket
。我一直在尋找到SO答案,但只能使用InputStream
和喜歡TCP傳輸解決方案找到。Unicode字符串
是否有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");
}
}