Connecting photon client to a python server

I am trying to create a TCP client application on my photon that will connect to a python server. The python server is up and running and when I flash the code over to the photon, it goes through the steps to create the TCPClient, but when it tries to connect to the server using the port and ip address specified, it cannot connect. The server doesn’t even seem to get a response.

TCP CLIENT CODE FOR PHOTON:

#define SERVER_IP {10, 202, 81, 104}
#define SERVER_PORT 8080


byte serverIP[] = SERVER_IP;
TCPClient client;

if( client.connect(serverIP, SERVER_PORT) ) {
    Spark.publish("connected");
}
else {
    Spark.publish("couldn't connect");
}

CODE FOR PYTHON SERVER:

import socket
import sys

# grab the host name so that I can grab the ip address
IP = socket.gethostbyname(socket.gethostname())
PORT = 8080


# create a TCP / IP socket
server_socket = socket.socket(socket.AF_INET, 
socket.SOCK_STREAM)
# bind the socket to a public host host and a port
server_socket.bind((IP, PORT))


# tell the socket to listen
# allows up to 5 queued connections
server_socket.listen(5)


# print out that we are listening
print("listening on: \n    IP:   " + IP + "\n    PORT: " + 
str(PORT))

# accept connections from outside
(connection, client_address) = server_socket.accept()
print("waiting for a connection")

# main loop
while True:

try:
    # let the user know it is connected to an photon
    print("connected to photon: " + client_address)

    data = connection.recv(2048)


    # recieve the data in small chunks

except socket.error as e:
    print(e)
finally:
    # clean up the connection and close it
    server_socket.close()

any ideas on why this wouldn’t be working?

@carthagecs, take a look at the docs regarding how to define and use an IP address:

https://docs.particle.io/reference/firmware/photon/#ipaddress

2 Likes

To expand on @peekay123’s reply.
There is another overload TCPClient::connect(const char *host, uint16_t port, network_interface_t=0) that will take your serverIP as host name rather than as IP.

One way to solve that is to add a dedicated IPAddress variable and use that (as pointed out in the docs).

2 Likes

thank you! that’s what I was looking for

1 Like