[英]Send message through Socket Outputstream from Swift Client to Java Server
As the title says, I'm having some problems connecting my Swift Client to a Java Server by using only native libraries.正如标题所说,我在仅使用本机库将 Swift 客户端连接到 Java 服务器时遇到了一些问题。
Right now I have a Java(client) to Java(server) connection, which works flawlessly, and a Swift(client) to Java(server) connection.现在我有一个 Java(客户端)到 Java(服务器)的连接,它可以完美地工作,还有一个 Swift(客户端)到 Java(服务器)的连接。 My Swift client does connect to the Java server (it shows on the console), but the readFully of my server hangs - the only thing I see is the enormous message length on the console and that's pretty much it.
我的 Swift 客户端确实连接到 Java 服务器(它显示在控制台上),但是我的服务器的 readFully 挂起 - 我唯一看到的是控制台上的巨大消息长度,仅此而已。
Swift Code (send): Swift 代码(发送):
func send(message: String) {
let data = "msg:\(message)".data(using: .utf8)!
data.withUnsafeBytes {
guard let pointer = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
print("Error joining chat")
return
}
out!.write(pointer, maxLength: data.count)
}
}
Java Server (read): Java 服务器(读取):
int lenght = in.readInt();
System.out.println("Message: " + lenght);
if(length>0){
byte[] message = new byte[length];
in.readFully(message), 0, message.length); //This is where the problem is
}
So, basically the Java server hangs on the readFully method.所以,基本上 Java 服务器挂在 readFully 方法上。 Any ideas why that is?
任何想法为什么会这样? Whether I send a simple String or a Byte array, it always hangs, and for some reason the length is extremely big.
无论我发送一个简单的字符串还是字节数组,它总是挂起,并且由于某种原因长度非常大。 Can someone help me understand what I'm doing wrong because I've around this for days and still didn't understand it (still pretty new to Swift).
有人可以帮我理解我做错了什么,因为我已经在这个问题上做了好几天但仍然不理解它(对 Swift 来说仍然很新)。
Thank you very much!非常感谢!
In your Java code, you expect the first 4 bytes to be the length of the message, but in the Swift code, you didn't send the length of the message first.在您的 Java 代码中,您希望前 4 个字节是消息的长度,但在 Swift 代码中,您没有先发送消息的长度。 You sent the message itself directly.
您直接发送了消息本身。 So now the Java code is left confused as to why the message is shorter than it expected, and waiting for more data to read.
因此,现在 Java 代码对于为什么消息比预期短,并等待读取更多数据感到困惑。
You can try sending the number of bytes in data
first:您可以尝试先发送
data
中的字节数:
let byteCountAsByteArray = withUnsafeBytes(of: Int32(data.count).bigEndian, Array.init)
out!.write(byteCountAsByteArray, maxLength: 4)
out!.write(pointer, maxLength: data.count)
I suspect that you are using a DataInputStream
in your Java code, hence .bigEndian
.我怀疑您在 Java 代码中使用了
DataInputStream
,因此.bigEndian
。 But if you are reading this in a little endian way, use .littleEndian
instead.但是,如果您以小端方式阅读本文,请改用
.littleEndian
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.