我在学习使用Java的套接字,并且成功将数据发送到在我自己的机器中运行的ServerSocket。当我尝试使用readline从这个套接字读取(所以我只能回应我自己发送的消息)我的程序挂起,不会返回。BufferedReader readLine方法挂起并阻止程序
下面的代码:
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是我定义的,所以我可以测试我的节目一个简单的界面上使用我homwework前摆一类。这里是代码:
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);
}
}
我的服务器非常简单。连接建立后,它进入这个循环并保持在这里,直到我关闭客户端(由于无限循环)。之后,一些异常处理将其返回到连接开始之前的位置。
while(true){
String msg = istream.readLine();
System.out.println("Arrived on server: " + msg); //just works on debug
ostream.writeUTF("ACK: " + msg);
ostream.flush();
}
我看不到我在想什么。
PS:奇怪的是,如果我调试服务器,我可以看到消息到达那里(例如我可以打印它),但如果我只是运行此代码,这是不可能的。这是否有一些我忽略的并发关系?
THX
服务器是做什么的?如果它没有回复你的消息,或者没有刷新它的写入,那么当然客户端将无限期地等待直到从服务器发送一行。 –
我将用服务器的无限循环编辑帖子,同时回复消息 –