【无标题】

项目场景:

基于Tcp一对多聊天室的构建原理实战


 

解决方案:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 接收客户端发送的消息
  */
class  ChatReceive extends Thread{
    private  Socket socket;
    public ChatReceive(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        this.receiveMsg();
    }
    /**
     * 实现客户端发送的信息
     */
    private void receiveMsg(){
        try(BufferedReader br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()))){
            while (true){
                String msg = br.readLine();
                synchronized ("abc"){
                    //把读到的数据写入到公共数据
                    ChatRoomServer.buf = "["+this.socket.getInetAddress()+"]"+msg;
                    //唤醒所有的发送对象
                    "abc".notifyAll();
                }

            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }



}


/**
 * 向客户端发送信息段
 *
 */
class ChatSend extends  Thread{
    private  Socket socket;
    public ChatSend(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        this.sendMessage();
    }
    /**
     * 将公共数据区信息发送给客户端
     */
    private  void sendMessage(){
        try(PrintWriter pw = new PrintWriter(this.socket.getOutputStream())){
            while (true){
                synchronized ("abc"){
                    //让发送消息的线程进入等待状态
                    "abc".wait();
                    pw.println(ChatRoomServer.buf);
                    pw.flush();
                }

            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }

}






public class ChatRoomServer {
    //定义公共数据区
    public static String buf;
    public static void main(String[] args) {
        System.out.println("Chat Server Version 1.0");
        System.out.println("Listen at 8888");
        try(ServerSocket socketserver = new ServerSocket(8888)){
            while (true){
                Socket socket =socketserver.accept();
                System.out.println("连接到:"+socket.getInetAddress());
                //接收信息的线程
                new ChatReceive(socket).start();

                //发送信息的线程
                new ChatSend(socket).start();
            }

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}

【无标题】_第1张图片

【无标题】_第2张图片 

 

你可能感兴趣的:(java,开发语言)