データを送受信したい (unicode utf-8 文字列を udp ソケットを介してDatagramSocket
)InputStream
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");
}
}