/*
キー入力した文字列UDPパケットを指定した host のport に送る
% DatagramSender host port
*/
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class SocketWrite {
    
    public static final int PACKET_SIZE = 1024;
    
    public static void main(String args[]) {
        DatagramSocket udpsocket = null;
        InetSocketAddress remoteAddress = // args[0] remote host name
            new InetSocketAddress(args[0], Integer.parseInt(args[1])); // port
        try{
            BufferedReader keyIn =
                new BufferedReader(new InputStreamReader(System.in));
            udpsocket = new DatagramSocket();
            String message;
            while ((message = keyIn.readLine()).length() > 0) {
                byte[] buf = message.getBytes();
                DatagramPacket packet = 
                    new DatagramPacket(buf, buf.length, remoteAddress);
                udpsocket.send(packet);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (udpsocket != null)
                udpsocket.close();
        }
    }
}
----------------------------------------------------------------
/*
UDP文字列パケットを指定した port から受け取る
% DatagramReceiver port
*/
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.io.IOException;

public class SocketRead{
    
    public static final int PACKET_SIZE = 1024;
    
    public static void main(String args[]) {
        DatagramSocket udpsocket = null;
        byte[] buf = new byte[PACKET_SIZE];
        DatagramPacket packet = 
            new DatagramPacket(buf, buf.length);
        try{ // args[0] ポート
            udpsocket = new DatagramSocket(Integer.parseInt(args[0]));
            System.out.println("起動中 port = " + udpsocket.getLocalPort());
            while (true) {
                udpsocket.receive(packet);
                String message = 
                    new String(buf, 0, packet.getLength());
                System.out.println(packet.getSocketAddress() + 
                    " 受信: " + message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (udpsocket != null)
                udpsocket.close();
        }
    }
}



▲トップページ > JAVA関連