简体   繁体   中英

Connecting to localhost server(python) using Alamofire

So i am trying to connect with the server side that i wrote in python(noob) with i simple Almofire.network call.

The python code is this:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)

while True:
# now our endpoint knows about the OTHER endpoint.
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")

and the swift is this:

   func preformCall( success: @escaping () -> Void, failure: @escaping () -> Void) {
    
     let url = "http://{my ip}:1234/"
     Alamofire.request(url, method: .get).responseJSON { (response) in
        if response.result.isFailure {
            failure()
        }
        
        if let data = response.data {
            let response = Response.init(data: data)

        }
    }
}

My ip - ip from.network preferences (mac) also i am connected to the same wifi.

If i take the same address to a browser i get this in the server side(terminal): Connection from ('127.0.0.1', 52084) has been established. Same when I connect to there sever with a simulator device it succeeded(url is - 127.0.0.1:1234), but when I try connecting from a real device it fails and I get this error:Code=-1004 "Could not connect to the server."

How can I test a connection from a real device and a localhost server?

So the answer was to listen to this address:0.0.0.0

     s.bind(("0.0.0.0", 1234))

0.0. 0.0 means all IPv4 addresses on the local machine

It seems as if your are lunching rest request instead of connecting to the server via sockets. i dont think alamoFire is build to handle sockets. Try this.

https://github.com/daltoniam/Starscream

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