2016-05-02 95 views
0

我无法将信息从客户端发送到服务器。 输出应该是:Java中的TCP服务器

*服务器:*
$>的Java的TcpClient /服务器IP/8080
用户当前客户端的ID:岩石//应该打印出来,但它没有
。 ..

客户
$>的Java TCPSERVER 8080
类型登录开始
登录 //用户输入
FROM SERVER:请使用您的用户名登录。
岩石 //用户输入
发送到服务器:岩石
...

但是服务器不打印出来的语句,它有需要缓冲或流做清洁向上?代码包含在下面。

TCPSERVER代码:

... 
BufferedReader inFromClient = new BufferedReader(
      new InputStreamReader(connectionSocket.getInputStream())); 
DataOutputStream outToClient = 
      new DataOutputStream(connectionSocket.getOutputStream()); 
... 
outToClient.writeBytes("Please log in with your user ID.\n"); 
String clientId = inFromClient.readLine() 
System.out.println("User ID of the current client: " + clientId); 
outToClient.writeBytes("Game has started!\n"); 

的TcpClient代码:

... 
    DataOutputStream outToServer = 
      new DataOutputStream(clientSocket.getOutputStream()); 
    BufferedReader inFromServer = new BufferedReader(
      new InputStreamReader(clientSocket.getInputStream())); 
    ... 
    System.out.println("Type login to start"); 
    if ((inFromUser.readLine()).equals(login)) 
    { 
      System.out.println("FROM SERVER: " + inFromServer.readLine()); 
      String option = inFromUser.readLine(); 
      outToServer.writeBytes(option); 
      System.out.println("Sent to Server: "+ option); 
      //should print "FROM SERVER: Game has started!" 
      System.out.println("FROM SERVER: " + inFromServer.readLine()); 
    } 
    ... 
+0

你试过'OutputStream.flush()'吗? –

+0

添加调试以查看发生了什么。什么'inFromUser.readLine()'返回,如果有的话? –

+1

每个'readLine()'结果都需要先检查为null,然后再执行其他任何操作。 – EJP

回答

1

你混合了字符流和字节流。一个DataOutputStream通常用于发送非字符数据。没有字段分隔符或行结束符,因为输入不应该是自由格式。一个整数将只发送4个字节,而不是\x0030\x0039之间的可变字符数。相反,BufferedReader用于面向行的字符数据。字符使用Charset编码,例如ASCIIUTF-16。取决于平台,行终止于\n\r\n

对于你看起来像你试图做的事情,应该使用PrintStream而不是DataOutputStream。 EG)为outToServer

PrintStream outToClient = new PrintStream(connectionSocket.getOutputStream(), true); 
    outToClient.println("Please log in with your user ID."); 

使用类似的代码。

注意:传递给PrintStream构造函数的值true可以在发送换行符时自动刷新,因此大多数#flush()调用变得不必要。


编辑

为了对称,因为你正在使用BufferedReader,我应该说使用PrintWriter。代替;以完全相同的方式使用:

PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true); 
outToClient.println("Please log in with your user ID."); 

最后一点:既PrintStreamPrintWriter抑制所有IOException秒。您应该定期使用#checkError()以确保未发生异常,例如流关闭。