简体   繁体   English

如何使用Java使TCP连接保持活动状态?

[英]How can I keep TCP connection alive with Java?

What I want to do is: 我想做的是:

1) Create a TCP socket listening to a particular port number in my local machine. 1)创建一个侦听本地计算机中特定端口号的TCP套接字。 ( Server ) (服务器)

2) Create another TCP socket that will connect to the first TCP socket I have created.( Client ) 2)创建另一个将与我创建的第一个TCP套接字连接的TCP套接字。(客户端)

3) Send some data to the Server via Client. 3)通过客户端向服务器发送一些数据。

4) Receive data by Client from the Server. 4)客户端从服务器接收数据。

5) Do NOT close the connection.. Wait for a little while.. 5)不要关闭连接。

6) Receive more data from the Server. 6)从服务器接收更多数据。

Here is my code: 这是我的代码:

public class MyTCPServer {

    public static void main(String argv[]) throws Exception {
        String clientSentence;
        String capitalizedSentence;
        ServerSocket welcomeSocket = new ServerSocket(6789);
        while (true) {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            System.out.println("Received: " + clientSentence);
            capitalizedSentence = clientSentence.toUpperCase() + '\n';
            outToClient.writeBytes(capitalizedSentence);
            outToClient.writeBytes(String.valueOf(System.currentTimeMillis()));
            Thread.sleep(1000);
            outToClient.writeBytes(String.valueOf(System.currentTimeMillis()));
        }
    }

}

So this TCP socket listens to port 6789. Please notice that it sends back the received String from the Client, uppercases it and returns it back. 因此,此TCP套接字侦听端口6789。请注意,它从客户端发送回接收到的字符串,将其大写并返回。 And then the Server sends the currentTimeMillis, waits for 1000 milliseconds, and sends the timeMillis again. 然后服务器发送currentTimeMillis,等待1000毫秒,然后再次发送timeMillis。

Here is my Client: 这是我的客户:

public class MyTCPClient {

    public static void main(String[] args) throws Exception {
        String sentence;
        String modifiedSentence;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        Socket clientSocket = new Socket("localhost", 6789);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');
        modifiedSentence = inFromServer.readLine();
        System.out.println("FROM SERVER: " + modifiedSentence);
    }

}  

However when I test my code I get: 但是,当我测试代码时,我得到:

Received: asdf
Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:115)
    at java.io.DataOutputStream.writeBytes(DataOutputStream.java:259)
    at MyTCPServer.main(MyTCPServer.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

How can I keep the connection alive in the Client side? 如何在客户端保持活动连接? Also I would like to be able to send more text from the Client as well. 我也希望能够从客户端发送更多文本。

The simplest thing would be to put a loop in the client code. 最简单的事情是在客户端代码中放入一个循环。 Something like this: 像这样:

   while ((modifiedSentence = inFromServer.readLine()) != null) {
       System.out.println("FROM SERVER: " + modifiedSentence);
       sentence = inFromUser.readLine();
       outToServer.writeBytes(sentence + '\n');
   }

The readLine() method blocks while waiting for messages from the server, so the client will not exit. 在等待来自服务器的消息时, readLine()方法将阻塞,因此客户端不会退出。

See bellow a simple tutorial on how to write a socket server and client: 下面是有关如何编写套接字服务器和客户端的简单教程:

http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

Your client exits. 您的客户退出。 It doesn't make any attempt to 'keep the connection alive'. 它不会进行任何尝试来“使连接保持活动状态”。 Your server writes data to the client that the client doesn't read. 您的服务器将客户端不读取的数据写入客户端。 So it gets exactly the exception that it should get. 因此,它得到了它应该得到的异常。 F you want to avoid the exception, add the missing reads. 如果要避免异常,请添加缺失的读段。

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

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