欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java使用Socket简单通讯详解

时间:2021-11-27 13:46:15|栏目:JAVA代码|点击:

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.不足之处

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

上一篇:解决使用RestTemplate时报错RestClientException的问题

栏    目:JAVA代码

下一篇:JAVA DOM解析XML文件过程详解

本文标题:Java使用Socket简单通讯详解

本文地址:http://www.codeinn.net/misctech/184985.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有