java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java使用Socket简单通讯

Java使用Socket简单通讯详解

作者:Aputonos

这篇文章主要介绍了Java使用Socket简单通讯详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

Java实现基于Socket的简单通信 

一.ServerSocket

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

等待客户端连接服务器

    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.同样的编写一个客户端界面

客户端界面

        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();

三.测试

简单实现

四.总结

1.原理流程

原理图

2.不足之处

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

到此这篇关于Java使用Socket简单通讯详解的文章就介绍到这了,更多相关Java使用Socket简单通讯内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文