Socket-멀티스레드를 통한 간단한 대화방 시뮬레이션

5385 단어
/**
 * Created by Liwei on 2016/7/17.
 *             
 *               ,                      
 */
public class MainChatRoom {
    public static void main(String[] args) throws SocketException {
        //        Socket
        DatagramSocket dsSend = new DatagramSocket();
        //        Socket ,     
        DatagramSocket dsReceive = new DatagramSocket(10086);

        SendThread sendThread = new SendThread(dsSend);
        ReceiveThread receiveThread = new ReceiveThread(dsReceive);

        Thread t1 = new Thread(sendThread);
        Thread t2 = new Thread(receiveThread);
        t1.start();
        t2.start();
    }

}

송신자 스레드:
public class SendThread implements Runnable {


    private DatagramSocket datagramSocket;

    /**
     *                 Socket   
     * @param datagramSocket
     */
    public SendThread(DatagramSocket datagramSocket){
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        try {
            //         
            BufferedReader br =
                    new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while ((line = br.readLine())!=null){
                if("886".equals(line)){
                    break;
                }
                byte[] bys = line.getBytes();
                DatagramPacket dp =
                        new DatagramPacket(bys,bys.length, InetAddress.getByName("192.168.100.112"),10086);
                //     
                datagramSocket.send(dp);
            }
            //     
            datagramSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

수신 스레드:
public class ReceiveThread implements Runnable {

    private DatagramSocket datagramSocket;

    public ReceiveThread(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        try {
            byte[] bys = new byte[1024];
            while (true) {
                DatagramPacket dp = new DatagramPacket(bys, bys.length);
                //     
                datagramSocket.receive(dp);

                //     

                String ip = dp.getAddress().getHostAddress();
                String data = new String(dp.getData(),0,dp.getLength());
                System.out.println("  ip "+ ip + "      :" + data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //    ,     Socket

    }
}

좋은 웹페이지 즐겨찾기