Socket —— 通过多线程简单模拟了聊天室

/**
 * 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

    }
}

你可能感兴趣的:(Socket —— 通过多线程简单模拟了聊天室)