我一直在尝试在测试客户端(用 Java 编写)和服务器(用 C#/.NET 编写)之间传输数据。
我尝试了 TCP 客户端和服务器,但目前存在刷新流的问题。我意识到刷新并不总是刷新流,所以我想知道是否有任何方法可以在没有 .flush() 的情况下或更可靠的方式刷新/发送流?
目前,客户端的重要部分是这样的(message是一个字符串,serverSocket是一个Socket对象):
OutputStream output = serverSocket.getOutputStream();
byte[] buffer = message.getBytes();
int length = buffer.length;
output.write(ByteBuffer.allocate(4).putInt(length).array());
output.write(buffer);
output.flush();
服务器看起来像这样:
NetworkStream stream = client.GetStream ();
byte[] sizeBuffer = new byte[4];
int read = stream.Read (sizeBuffer, 0, 4);
int size = BitConverter.ToInt32 (sizeBuffer, 0);
Databaser.log ("recieved byte message denoting size: " + size);
byte[] messageBuffer = new byte[size];
read = stream.Read (messageBuffer, 0, size);
string result = BitConverter.ToString (messageBuffer);
Databaser.log ("\tmessage is as follows: '" + result + "'");
如果从代码中看不出来,客户端发送 4 个字节,这些字节被组合成一个 32 位整数,这就是消息的长度。然后我根据该长度读取消息,并使用内置转换器将其转换为字符串。
正如我所说,我想知道如何刷新连接?我知道这段代码并不完美,但我可以将其更改回当我通过网络使用 TCP 和 UTF 独占字符串消息传递时,但无论哪种方式,连接都不会从客户端发送任何内容,直到客户端关闭或关闭连接。
最佳答案
也许问题出在字节顺序上。我有一个从平板电脑 (java) 发送到 C# 应用程序 (Windows Intel) 的应用程序,我使用的方法与您所做的类似,但以下内容除外
ByteBuffer iLength = ByteBuffer.allocate(4);
iLength.order(ByteOrder.LITTLE_ENDIAN);
iLength.putInt(length);
output.write(iLength.array(), 0, 4);
output.write(buffer);
output.flush();
Java 使用 BIG-ENDIAN,Intel 使用 LITTLE-ENDIAN 字节顺序。
关于java - 在客户端和服务器之间传输数据并动态刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090529/