TCP连接-服务器仅在关闭套接字后发送消息 [英] TCP connection - server only sends message after closing socket

查看:113
本文介绍了TCP连接-服务器仅在关闭套接字后发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让客户端向服务器发送请求并接收响应,同时保持连接状态.

I am trying to make a client send a request to a server and receive a response whilst keeping to connection up.

如果我关闭插座:

//server side
outToClient.writeBytes("Message to send");
connectionSocket.close();

//client side
serverResponse = inFromServer.readLine(); 
System.out.println("FROM SERVER: " + serverResponse);

客户端输出

从服务器:要发送的消息

FROM SERVER: Message to send

然后显然失去了连接.

如果我不关闭插座:

//server side
outToClient.writeBytes("Message to send");

//client side
serverResponse = inFromServer.readLine(); 
System.out.println("FROM SERVER: " + serverResponse);

客户端无输出. 服务器从不发送消息,或者客户端从不接收消息.

No output on client side. The server never sends the message or the client never receives it.

有人知道发生这种情况的可能原因吗? 客户端使用一个线程来接收消息,并使用一个线程来发送消息.客户端套接字是在主客户端线程中创建的,因此接收方线程和发送方线程使用当前套接字进行通信.

Anyone knows a possible reason for this to be happening? The client uses a thread to receive messages and a thread to send messages. The client socket is created in the main client thread so receiver and sender threads use the current socket to communicate.

谢谢.

推荐答案

如果客户端希望读取一行,则服务器应写一行.一行以\n字符结尾.

If the client expects to read a line, the server should write a line. A line is terminated by a \n character.

可能还需要刷新用于向客户端发送数据的流:

It may also be necessary to flush the stream you are using to send data to the client:

outToClient.writeBytes("Message to send\n");
outToClient.flush();

没有看到代码,很难说是否需要刷新.

Without seeing the code it's hard to say if the flush is required or not.

这篇关于TCP连接-服务器仅在关闭套接字后发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆