简体   繁体   中英

Sending Message Over TCP in 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)
}

The code works great but my problem is that the connection succeed only if the simulator is not on a real iphone (my iphone), but only on their simulators. I don't know how to solve it and what is the problem. When I print the errmsg it shows me:"connection timeout".

Could you try to set your host ip as the ip of your computer?

let client:TCPClient = TCPClient(addr: "your computer ip", port: 8080)

I guess that it works on simulator because the simulator share network with your real computer, so in case of connecting from external such as your phone I think you should try to replace localhost ip with the ip of your computer where running your server.

One more thing is that your server is probably local server, so ensure it and the phone connect in the same network.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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