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
Related
I made a program using Python that should connect to the server using a socket. I run the script on the same machine and when I tried with private ip it worked but public doesn't.
Client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("46.126.xx.xxx",9454)) #I put the public ip of the server (same machine)
msg = s.recv(1024)
print(msg.decode("utf-8"))
Server
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("0.0.0.0",9454))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established!")
clientsocket.send(bytes("Welocme to the server", "utf-8"))
It does not give me any errors. I made lots of reasearch but couldn't figure out what the problem is.
Well I just put the public ip of the server in the client socket.connect() and expected it to connect but it didn't. I am running this on the same machine.
I'm coding in Python and I'm looking for a way to connect to a website port using sockets so that I can send commands to the server. My code is:
import socket
HOST = 'www.google.com'
PORT = 80
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(5)
This code is giving me an error "The requested address is not valid in its context". How do I do this?
You're trying to bind on Google's IP, which doesn't make sense because there isn't a network adapter connected to your computer with that IP (thus the error). You're mixing up creating a server and being a client connecting to a remote server. You want to connect to the Google server:
import socket
HOST = 'www.google.com'
PORT = 80
socket = socket.socket()
socket.connect((HOST, PORT))
# Send an HTTP GET request to request the page
socket.send(b"""
GET / HTTP/1.1
Host: www.google.com
""")
msg = socket.recv(8192)
print(msg)
I have been searched all over the web and all examples with an ip address and port number connect like how I've done it.
def on_connect(self):
if self.button1['text'] == "Connect":
try:
#host = str(self.ltext1.get())
#port = int(self.spin1.get())
host="127.0.0.1"
port=502
tcpsocket= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_adress = (host,port)
tcpsocket.connect(server_adress)
print("sdsd")
self.button1['text'] = "Disconnect"
except:
print("failed")
else:
tcpsocket.close()
self.button1['text'] = "Connect"
For me I have a server open at that port and I have successfully connect to it using a C++ client application but when I connect with the same ip address and port number it enter the except meaning the connect failed and my server does not even inform me of any attempt to connect(it does for the C++ client).
Where have I gone wrong in my code or what could possibly be the problem. I also disconnect and close the C++ client application to free up the port for my client.
I'm building a simple chat app using python and want to use it over the internet. The server is starting on my local machine which has the port already forwarded, and to allow other users to access I provided them with the IP address I got from www.whatismyip.com. However, every time I test the application the client side gets this error :
client_socket.connect((ip,port))
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection failed because connected host has
failed to respond
The server side is like this :
import socket
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
port = 5000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((ip,port))
server_socket.listen()
print(f"Server started on {ip}:{port}")
...
And the client side :
import socket
ip = "41.102.XXX.XX"
port = 5000
username = input("Username : ").encode('utf-8')
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((ip,port))
client_socket.send(username)
...
If you are behind a router/NAT, and the PC where your server is has a LAN IP address, then you have to configure port forwarding in the router/NAT from port 5000 to port 5000 in the local IP address.
Other 2 possibilities: 1) the client is not sending the packets to the correct IP address, maybe not through the correct network interface. To check this you can use wireshark in the client machine. 2) there is some firewall rule in the server dropping the incoming messages. This is possible if you're getting the error after more than one minute. This usually happens when after the TCP SYN message there is no TCP SYN/ACK message. And not seeing the SYN/ACK is because the SYN message doesn't get to the server's listening port.
I'm trying to copy the features of this library https://github.com/rnbguy/pysphere/blob/master/misphere.py which connects via websockets to the Mi Sphere 360 camera.
The important code is here
ms_ip = '192.168.42.1'
ms_tcp_port = 7878
ms_uk_port = 8787
ms_fs_port = 50422
def init(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.socket.connect((self.ms_ip, self.ms_tcp_port))
self.socket_1 = socket.socket()
self.recv_handle_live = True
self.recv_thread = threading.Thread(target=self.recv_handler)
self.recv_thread.daemon = True
self.session = Session()
self.session.conf = {}
self.session.locks = {}
self.last_send = 0
I'm trying to do this with the ws library in Node
const ip = '192.168.42.1'
const port = '7878'
const url = `ws://${ip}:${port}`
const websocket = new WebSocket(url)
However I'm not getting a connection to the camera. (It's connected via Wifi, but the websocket never sends a connection message)
I'm wondering if it's to do with the protocols, which are listed in the Phython code.
I see in the websocket documentation you can define protocols in the connection, but I can't find any documentation about what those protocols are and how you add them.
i.e.
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
Anyone know how I add something like this in the Node websocket connection?
A webSocket connection cannot be made to a plain TCP socket server.
A plain TCP socket is not the same as a webSocket. Your Python code appears to be making a plain TCP socket connection.
Your node.js code is attempting to make a webSocket connection. A webSocket connection can only be made to a webSocket server that speaks the webSocket protocol (which runs on top of a plain TCP socket).
If your Python code is working, then you apparently need to make just a plain TCP socket connection which you can see how to do in the Net module.
For further description of the differences between a plain TCP connection and a webSocket connection see these:
Computer refuses websocket connections
What's the difference between WebSocket and plain socket communication?
Is there a way to do a tcp connection to an IP with javascript?
Socket server not connect with JavaScript socket client
To connect to a regular TCP socket, use net package instead of a WebSocket. Example Node equivalent code:
const net = require('net');
const port = 7878
const ip = "192.168.42.1"
const socket = net.createConnection(port, ip);
socket.on('connect', () => {
console.log("socket connected");
});