微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – TCP客户端/服务器通信只发送第一条消息?

我在java中设置一个简单的TCP客户端服务器交互.

服务器:

服务器是用Java编写的桌面客户端:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.socket;

class Tcpserver
{
    public static int PORT_NUMBER = 6129;

    public static void main(String argv[]) throws Exception
    {
        String clientMessage;
        ServerSocket welcomeSocket = new ServerSocket(PORT_NUMBER);

        while (true)
        {
            Socket connectionSocket = welcomeSocket.accept();

            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getoutputStream());

            clientMessage = inFromClient.readLine();

            System.out.println("Received: " + clientMessage);

            outToClient.writeBytes("I received this: "+ clientMessage +"\n");
        }
    }
}

客户:

客户端是一个Android应用程序,通过TCP连接到服务器.在客户端我有一个方法sendMessage(String msg),它尝试向服务器发送消息.

public static void sendMessage(String msg) throws IOException
{
    if (mainSocket == null)
    {
        return;
    }
    if (!mainSocket.isConnected())
    {
        connectSocket();
    }
    PrintWriter output = new PrintWriter( mainSocket.getoutputStream());
    output.println(msg);
    output.flush();
    System.out.println(msg);
}

问题是,服务器收到第一条消息,但任何后续消息都不会显示.当我关闭客户端时,所有其他消息突然出现在服务器中.

这是服务器看到的:

Received: message 1

很长一段时间都没有活动……
然后我关闭了客户端

Received: message 2 message 3 message 4 message 5 etc..

我在sendMessage()方法中放了一个println,并且实时调用方法本身.

解决方法:

每次发送消息时,您都需要在客户端显式关闭()PrintWriter.当您完成读取inFromClient时,在服务器端也是如此,并且当您完成写入outToClient时再次.

另见这篇basic example,他们很好地解释了基本的工作流程:

However, the basics are much the same as they are in this program:

Open a socket.

Open an input stream and output stream to the socket.

Read from and write to the stream according to the server’s protocol.

Close the streams.

Close the socket.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐