简体   繁体   English

在Swift中通过TCP发送消息(NULL终止)

[英]Sending Message Over TCP in Swift (NULL terminated)

I am using swift socket library with the following code: 我正在使用带有以下代码的swift套接字库:

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)
}

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? 该代码很好用,但是我的问题是我的服务器获取的数据没有空终止符,如您在下一个链接中所见: https : //gyazo.com/1a6576b515d37c9400a58ac67bfa2350我该怎么办?

Presuming you are using this library , there is a bug in the implementation of TCPClient.send(str:) , as it uses strlen per this line . 假设您正在使用此库 ,则TCPClient.send(str:)的实现中存在一个错误,因为它在此行中使用strlen strlen will terminate at the first NUL character. strlen将在第一个NUL字符处终止。

Change your code to: 将您的代码更改为:

 var (success, errmsg) = client.send(data:Array<UInt8>("|~\0".utf8))

and you should be good 你应该很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM