在Swift中通过TCP发送消息(NULL终止) [英] Sending Message Over TCP in Swift (NULL terminated)
本文介绍了在Swift中通过TCP发送消息(NULL终止)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用swift套接字库与以下代码:
I am using swift socket library with the following code:
let client:TCPClient = TCPClient(addr: "127.0.0.1", port: 8080)
var (success,errmsg)=client.connect(timeout: 1)
if success{
var (success,errmsg)=client.send(str:"|~\0" )
if success{
let data=client.read(1024*10)
if let d=data{
if let str=String(bytes: d, encoding: NSUTF8StringEncoding){
print(str)
}
}
}else{
print(errmsg)
}
}else{
print(errmsg)
}
但我的问题是,我的服务器获取的数据没有null终止符,你可以看到在下一个链接: https:// gyazo .com / 1a6576b515d37c9400a58ac67bfa2350
我该怎么办?
The code works great but my problem is that my server gets the data without null-terminator, as you can see in the next link: https://gyazo.com/1a6576b515d37c9400a58ac67bfa2350 What can I do?
推荐答案
假设您使用这个库,在执行时有一个错误TCPClient.send(str:)
,因为它使用 strlen
每此行。 strlen
将在第一个 NUL
字符处终止。
Presuming you are using this library, there is a bug in the implementation of TCPClient.send(str:)
, as it uses strlen
per this line. strlen
will terminate at the first NUL
character.
将代码更改为:
var (success, errmsg) = client.send(data:Array<UInt8>("|~\0".utf8))
你应该很好
这篇关于在Swift中通过TCP发送消息(NULL终止)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文