Java TCP发送第一条消息,然后无限等待

标签 java tcp

我的问题基于以下代码:

  • 运行 TCPServer.java
  • 然后运行 ​​TCPClient.java

我希望有客户端打印出来

服务器说(1):嘿伙计 1

服务器说(2):嘿老兄2

...但它只是停留在 HEY DUDE 1 上。我在做什么却没有产生我想要的结果?

TCPServer.java

import java.io.*;
import java.net.*;

class TCPServer {
    public static void main (String args[]) throws Exception{
        new TCPServer();
    }
    TCPServer() throws Exception{
        //create welcoming socket at port 6789
        ServerSocket welcomeSocket = new ServerSocket(6789);

        while (true) {
            //block on welcoming socket for contact by a client
            Socket connectionSocket = welcomeSocket.accept();
            // create thread for client
            Connection c = new Connection(connectionSocket);
        }
    }
    class Connection extends Thread{
        Socket connectionSocket;
        Connection(Socket _connectionSocket){
            connectionSocket = _connectionSocket;
            this.start();
        }
        public void run(){
            try{
                //create input stream attached to socket
                BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connectionSocket.getInputStream()));
                //create output stream attached to socket
                PrintWriter outToClient = new PrintWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
                //read in line from the socket
                String clientSentence = inFromClient.readLine();
                System.out.println("Client sent: "+clientSentence);
                //process
                String capitalizedSentence = clientSentence.toUpperCase() + '\n';
                //write out line to socket
                outToClient.print(capitalizedSentence);
                outToClient.flush();
            }catch(Exception e){}
        }
    }
}

TCP客户端.java

import java.io.*;
import java.net.*;

class TCPClient {
    //String name="";
    String host = "localhost";
    int port = 6789;
    Socket socket = null;
    public static void main(String args[]) throws Exception{
        TCPClient client = new TCPClient();
        client.SendToServer("Hey dude 1");
        System.out.println("Server Said(1): "+client.RecieveFromServer());
        client.SendToServer("Hey dude 2");
        System.out.println("Server Said(2): "+client.RecieveFromServer());
        client.close();
    }

    TCPClient(String _host, int _port) throws Exception{
        host = _host;
        port = _port;
        socket = new Socket(host, port);
    }
    TCPClient() throws Exception{
        socket = new Socket(host, port);
    }
    void SendToServer(String msg) throws Exception{
        //create output stream attached to socket
        PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        //send msg to server
        outToServer.print(msg + '\n');
        outToServer.flush();
    }
    String RecieveFromServer() throws Exception{
        //create input stream attached to socket
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader (socket.getInputStream()));
        //read line from server
        String res = inFromServer.readLine(); // if connection closes on server end, this throws java.net.SocketException 
        return res;
    }
    void close() throws IOException{
        socket.close();
    }
}

最佳答案

您的服务器线程在您处理完第一条消息后立即结束。您需要将服务器代码放入这样的循环中:

String clientSentence;
while ((clientSentence = inFromClient.readLine()) != null) {
    System.out.println("Client sent: "+clientSentence);
    //process
    String capitalizedSentence = clientSentence.toUpperCase() + '\n';
    //write out line to socket
    outToClient.print(capitalizedSentence);
    outToClient.flush();
}

关于Java TCP发送第一条消息,然后无限等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16636291/

相关文章:

java - 定义带有别名和空值的 spring bean

java - 是否有删除双向链表边的一半的名称?

tcp - IANA(端口号注册表)保存在哪里?

c++ - 带有 boost asio 的 TIME_WAIT

java - 解析 JSON 数据时应用程序崩溃

java - 我无法导入 com.itextpdf.text.Document 类

java - 使用 spring-boot 在依赖注入(inject)中创建 bean 时出错

objective-c - 使用GCDASyncSocket时如何分离数据包

c++ - 如何使用 boost::asio::ip::tcp::resolver 处理本地和公共(public) ip

c - 运行非阻塞 TCP 代码时出现 memcheck 错误