Sending Message Over TCP in Swift (NULL terminated)

浪尽此生 提交于 2019-12-12 04:30:29

问题


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

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?


回答1:


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.

Change your code to:

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

and you should be good



来源:https://stackoverflow.com/questions/36873306/sending-message-over-tcp-in-swift-null-terminated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!