问题描述
我正在尝试使用 Java 学习套接字,并且我成功地将数据发送到在我自己的机器上运行的 ServerSocket.当我尝试使用 readline 从这个套接字读取时(所以我可以只回显我自己发送的消息)我的程序挂起并且不会返回.
I'm trying to learn sockets using Java and I sucessfully sent data to a ServerSocket running in my own machine. When I try to read from this socket using readline (so I can just echo my own sent message) my program hangs and won't return.
代码如下:
public static void main(String[] args) throws UnknownHostException, IOException {
TCPClient cli = new TCPClient("127.0.0.1", "15000");
try {
cli.ostream.writeUTF("Teste");
String echo = cli.istream.readLine(); //it hangs in this line
System.out.println(echo);
}
TCPClient 是我定义的一个类,因此我可以在我的工作中使用 Swing 之前在更简单的界面上测试我的程序.这是代码:
TCPClient is a class I defined so I can test my program on a simpler interface before using swing on my homwework. here's the code:
public class TCPClient {
public DataOutputStream ostream = null;
public BufferedReader istream = null;
public TCPClient(String host, String port) throws UnknownHostException {
InetAddress ip = InetAddress.getByName(host);
try {
Socket socket = new Socket(host, Integer.parseInt(port));
ostream = new DataOutputStream(socket.getOutputStream());
istream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
我的服务器很简单.连接建立后,它进入这个循环并一直停留在这里直到我关闭客户端(因为无限循环).之后,一些异常处理将其返回到连接开始之前的点.
My server is pretty simple. After the connection is estabilished, it enters in this loop and stays here until I close the client (because of the infinite loop). Afterwards, some exception handling returns it to the point before the connection started.
while(true){
String msg = istream.readLine();
System.out.println("Arrived on server: " + msg); //just works on debug
ostream.writeUTF("ACK: " + msg);
ostream.flush();
}
我不知道我错过了什么.
I don't see what am I missing.
PS:奇怪的是,如果我调试服务器,我可以看到到达那里的消息(例如,我可以打印它),但是如果我只运行此代码,这是不可能的.这是否有一些我忽略的并发关系?
PS: the wierd stuff is that if I debug the server, I can see the message arriving there (I can print it, for example), but this isn't possible if I just run this code. Does this have some concurrency relation I'm overlooking?
谢谢
推荐答案
问题在于 readLine
尝试读取一行.在确定到达行尾之前,它不会返回该行.这意味着它需要换行符或通信结束.由于服务器不发送任何换行符并且不关闭流,因此客户端无限期地等待.
The problem is that readLine
tries reading a line. It will not return the line until it's sure that the end of line has been reached. This means that it expects either a newline character, or the end of the communication. Since the server doesn't send any newline char and doesn't close the stream, the client waits indefinitely.
这篇关于BufferedReader readLine 方法挂起并阻塞程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!