我正在c#中编写tcp服务器,在java中编写相应的客户端。我正在测试localhost上的连接,客户端能够连接到服务器。但是,当我发送消息时,客户端永远不会收到消息。使用调试器我已经验证了stream.Write(...)的执行。知道问题可能是什么?
这是c#服务器:
TcpClient client = (TcpClient)cl;
NetworkStream stream = client.GetStream();
byte[] msg = new byte[512];
int bytesRead;
while (running)
{
while (messages.getCount() > 0)
{
String msg = messages.Take();
if (cmd != null)
{
byte[] bytes = Encoding.UTF8.GetBytes(msg.ToCharArray());
try
{
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
}
catch (Exception e)
{
}
}
}
Thread.Sleep(1000);
}
Java客户端:
public void run()
{
try
{
socket = new Socket(address, port);
in = new BufferedReader( new InputStreamReader( socket.getInputStream() ));
out = new PrintWriter(socket.getOutputStream());
running = true;
}
catch (Exception e){
e.printStackTrace();
running = false;
}
String data;
while(running)
{
try
{
data = in.readLine();
if(data != null)
{
processData(data);
}
}
catch (IOException e)
{
e.printStackTrace();
running = false;
break;
}
}
try
{
socket.close();
socket = null;
}
catch (IOException e)
{
e.printStackTrace();
}
running = false;
}
答案 0 :(得分:5)
您正在使用BufferedReader.readLine()
。您的消息字符串是否由CR,LF或CR / LF终止?
readLine
阻塞,直到读取行终止字符。