简体   繁体   English

Java无法同时读写套接字

[英]Java cannot read and write to socket at the same time

I am trying to build a simple multi client chat application using java sockets. 我正在尝试使用Java套接字构建一个简单的多客户端聊天应用程序。 The way I have gone about doing this is by having a client class that connects to a server class that waits for clients to connect and creates a new thread to deal with that client(Where the socket connection is read and written to). 我这样做的方法是让客户端类连接到服务器类,该服务器类等待客户端连接并创建一个新线程来处理该客户端(在其中读取和写入套接字连接)。 The client also reads from and writes to the socket connection to this thread. 客户端还读取和写入与此线程的套接字连接。 However, when the client wrote to the output stream of the socket, the server would not respond. 但是,当客户端写入套接字的输出流时,服务器将不会响应。 A similar question here was posted: 这里发布了一个类似的问题:

Can you write to a sockets input and output stream at the same time? 您可以同时写入套接字的输入和输出流吗?

One of the answers here says that you can read and write to a socket at the same time as long as reading from the socket is done on a separate thread. 这里的答案之一是,您可以同时读取和写入套接字,只要在单独的线程中完成对套接字的读取即可。

Here is my client application: 这是我的客户应用程序:

    public class Client {

    Socket socket;

    public static void main(String[] args) {
        new Client();
    }

    public Client() {
        try {
            socket = new Socket("localhost", 4444);

            new Thread() {

                @Override
                public void run() { //read from the input stream

                    try(
                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    ) {
                        String line;
                        while( (line = in.readLine()) != null ) {
                            System.out.println("Server said: " + line);
                        }
                    } catch(IOException e) {

                    }

                }

            }.start();

            //write to output stream
            try(
                PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                Scanner userInput = new Scanner(System.in);
            ){
                System.out.println("Enter Something: ");
                if(userInput.hasNextLine()) {
                    out.println(userInput.nextLine());
                }
            } catch (IOException e) {

            }

        } catch(IOException e) {

        }


    }
}

And my server application: 而我的服务器应用程序:

public class Server {
    ServerSocket ss;


    public static void main(String[] args) {
        new Server();
    }

    public Server() {
        System.out.println("Server Running...");
        try {
            ss = new ServerSocket(4444);

            while(true) {


                Socket socket = ss.accept();
                new Thread() { //create new thread connection to client
                    @Override
                    public void run() {

                        new Thread() { //thread that reads inputstream
                            @Override
                            public void run() {

                                try(
                                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                ) {
                                    String line;
                                    while( (line = in.readLine()) != null ) {
                                        System.out.println("Client said: " + line);
                                        //The problem seems to lie here.
                                    }
                                } catch(IOException e) {

                                }

                            }
                        }.start();

                        //write to outputstream
                        try (
                            PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                        ) {
                            String sendToClient = "Hey, my name is Server007 B)";

                            out.println(sendToClient);

                        } catch(IOException e) {

                        }
                    }
                }.start();

            }


        } catch (IOException e) {}
    }
}

I will run the server, then run the client, on the client side the output is 我将运行服务器,然后运行客户端,在客户端输出

Server said: Hey, my name is Server007
Enter something: 
Hello! <- enter anything

but the server does not print 'Client said: Hello!' 但服务器不打印“客户说:您好!” like I expected it to. 就像我期望的那样。 I hope I made my problem clear enough, thanks. 我希望我的问题已经足够清楚了,谢谢。

Ok, so I figured it out, I will answer my own question in case anyone makes the same mistake. 好的,所以我弄清楚了,如果有人犯同样的错误,我将回答我自己的问题。 The PrintWriter constructor should be this: PrintWriter构造函数应为:

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

Not this: 不是这个:

PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

Alternatively, I could have done this: 或者,我可以这样做:

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

I must have just gotten confused between BufferedWriter and PrintWriter :P 我一定对BufferedWriter和PrintWriter:P感到困惑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM