Java实现基于Socket的简单通信

Java实现基于Socket的简单通信

  • 一.ServerSocket
    • 1.使用JavaFX写的小界面,方便观察客户端连接情况
    • 2.创建ServerSocket并处理客户端连接并显示客户端基本信息
    • 3.新建Handle类处理接收发送两个客户端的消息
  • 二.Socket
    • 1.同样的编写一个客户端界面
    • 2.创建Socket连接客户端并获取输入输出流
    • 3.添加编辑框监听处理消息发送
    • 4.创建新线程从服务器上接收消息
  • 三.测试
  • 四.总结
    • 1.原理流程
    • 2.不足之处

一.ServerSocket

1.使用JavaFX写的小界面,方便观察客户端连接情况

Java实现基于Socket的简单通信_第1张图片

    TextArea ta = new TextArea();
        Scene scene = new Scene(new javafx.scene.control.ScrollPane(ta), 450, 200);
        primaryStage.setTitle("Server");
        primaryStage.setScene(scene);
        primaryStage.show();

2.创建ServerSocket并处理客户端连接并显示客户端基本信息

两个客户端连接后进行通信,未能实现动态处理。

        new Thread(() -> {
            try {
                ServerSocket serverSocket = new ServerSocket(8000);
                Platform.runLater(() -> {
                    ta.appendText(new Date() + " : Server started at "  + "\n");
                    ta.appendText(new Date() + " : wait to persons to join the chat" + "\n");
                });

                while (true){
                    Socket person1 = serverSocket.accept();
                    number++;
                    InetAddress inetAddress1 = person1.getInetAddress();
                    Platform.runLater(() -> {
                        ta.appendText(new Date() + ": Person"  + number + "joined the chat" + "\n");
                        ta.appendText(new Date() + ": Person"  + number + "'s host name is " + inetAddress1.getHostName() + "\n");
                        ta.appendText(new Date() + ": Person"  + number + "'s host address is " + inetAddress1.getHostAddress() + "\n");
                        ta.appendText(new Date() + ": wait for Person2 " + "\n");
                    });

                    Socket person2 = serverSocket.accept();
                    number++;
                    InetAddress inetAddress2 = person2.getInetAddress();
                    Platform.runLater(() -> {
                        ta.appendText(new Date() + ": Person"  + number + "joined the chat" + "\n");
                        ta.appendText(new Date() + ": Person"  + number + "'s host name is " + inetAddress2.getHostName() + "\n");
                        ta.appendText(new Date() + ": Person"  + number + "'s host address is " + inetAddress2.getHostAddress() + "\n");
                        ta.appendText(new Date() + ": Start the chat " + "\n");
                    });

                    new Thread(new HandleChat(person1,person2)).start();

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

3.新建Handle类处理接收发送两个客户端的消息

只实现了一人一句的效果,没有实现一人连续发送消息对方也能正确接收。

    class HandleChat implements Runnable{
        Socket person1;
        Socket person2;

        public HandleChat(Socket person1,Socket person2){
            this.person1 = person1;
            this.person2 = person2;
        }
        @Override
        public void run() {
            try {
                DataInputStream fromPerson1 = new DataInputStream(person1.getInputStream());
                DataOutputStream toPerson1 = new DataOutputStream(person1.getOutputStream());
                DataInputStream fromPerson2 = new DataInputStream(person2.getInputStream());
                DataOutputStream toPerson2 = new DataOutputStream(person2.getOutputStream());

                while (true){

                    String passage1 = fromPerson1.readUTF();
                    toPerson2.writeUTF(passage1);
                    String passage2 = fromPerson2.readUTF();
                    toPerson1.writeUTF(passage2);

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

思考后将HandleChat类中对两个客户端的接收发送消息处理放在两个线程中,就可以实现两个客户端自由通信。

            new Thread(() -> {
                while (true) {
                    try {
                        String passage2 = fromPerson2.readUTF();
                        toPerson1.writeUTF(passage2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            }).start();


            new Thread(() -> {
                while (true) {
                    try {
                        String passage1 = fromPerson1.readUTF();
                        toPerson2.writeUTF(passage1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

二.Socket

1.同样的编写一个客户端界面

Java实现基于Socket的简单通信_第2张图片

        BorderPane pane = new BorderPane();
        pane.setPadding(new Insets(5));
        pane.setStyle("-fx-border-color: green");
        pane.setLeft(new Label("Enter a radius: "));

        TextField tf = new TextField();
        tf.setAlignment(Pos.BASELINE_RIGHT);
        pane.setCenter(tf);

        BorderPane mainPane = new BorderPane();
        TextArea ta = new TextArea();
        mainPane.setCenter(new ScrollPane(ta));
        mainPane.setTop(pane);

        Scene scene = new Scene(mainPane,450,200);
        primaryStage.setTitle("Client");
        primaryStage.setScene(scene);
        primaryStage.show();

2.创建Socket连接客户端并获取输入输出流

        try {
//            创建一个连接服务器端的Socket
            Socket socket = new Socket("localhost",8000);
//            获得输入输出流
            toServer = new DataOutputStream(socket.getOutputStream());
            fromServer = new DataInputStream(socket.getInputStream());

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

3.添加编辑框监听处理消息发送

//        编辑框事件监听
        tf.setOnAction(e ->{
            String passage = tf.getText().trim();
            tf.clear();
            try {
                toServer.writeUTF(passage);
                toServer.flush();
                ta.appendText("Me "  + ": " + passage + "\n");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        });

4.创建新线程从服务器上接收消息

//        新线程从服务器读取信息
        new Thread(() -> {
            while (true) {
                try {
                    String passage = fromServer.readUTF();
                    ta.appendText("He : " + passage + "\n");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

三.测试

Java实现基于Socket的简单通信_第3张图片

四.总结

1.原理流程

Java实现基于Socket的简单通信_第4张图片

2.不足之处

只是简单实现了静态两客户端聊天的功能,并且只能够第一个链接上的用户先发送消息,且一人发送消息后只能等待接收另一个人的消息后才能再次发送消息。之后的时间希望能加以改进。

你可能感兴趣的:(Java实现基于Socket的简单通信)