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.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...