UDP 기반 Socket 멀티스레드 통신 단순화

4732 단어 Socket
            

public class Client {
    public static void main(String[] args) throws IOException {
        InetAddress address = InetAddress.getByName("127.0.0.1");
        int port = 8888;
        byte[] bytes= "              ".getBytes();
        DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length,address,port);
        DatagramSocket datagramSocket = new DatagramSocket();
        datagramSocket.send(datagramPacket);

        byte[] bytes2 = new byte[1024];
        DatagramPacket datagramPacket2 = new DatagramPacket(bytes2, bytes2.length);
        datagramSocket.receive(datagramPacket2);

        String data = new String(bytes2,0,bytes.length);
        System.out.println(data);
    }

}
/*
 *   udp    
 */
public class Server {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(8888);
        System.out.println("          ");
        while (true) {
            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

            datagramSocket.receive(datagramPacket);
            String a = new String(bytes,0,bytes.length);
            System.out.println(a);

            ServerThread serverThread = new ServerThread(datagramSocket,datagramPacket);
            //                     ,      
            serverThread.setPriority(4);//       ,  【1,10】   5
            serverThread.start();

        }

    }
}
public class ServerThread extends Thread {
    public DatagramSocket datagramSocket;
    public DatagramPacket datagramPacket;
    public ServerThread(DatagramSocket datagramSocket,DatagramPacket datagramPacket){
        this.datagramSocket = datagramSocket;   
        this.datagramPacket = datagramPacket;

    }
    @Override
    public void run() {
        try {                   
            byte[] bytes2 ="  ".getBytes();
            InetAddress address = datagramPacket.getAddress();
            int port = datagramPacket.getPort();
            DatagramPacket datagramPacket2 = new DatagramPacket(bytes2, bytes2.length,address,port);
            datagramSocket.send(datagramPacket2);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

좋은 웹페이지 즐겨찾기