I am facing a strange problem using a simple python client/server example. After having established the connection for the first time, if I tried to send the message "get id", I don't get any answer from my server and client side is stuck (I am developping an application to communicate with a measurement system via ethernet instead of RS232 and "get id" is one of the command we use). However if I start by sending "a" or "1" or even "hello world", the server answers and then if I send "get id" it works !
Now if I run the server code and use Putty as client, I can send "get id" as a first message and the server answers without any problem !
I would like to understand what is going on...
Here is the client code
import socket
host = '192.168.0.102'
port = 12800
connection_with_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection_with_server.connect((host, port))
print("Connexion established on port {}".format(port))
msg = '1'
while msg != b'stopall\r':
msg = input('> ')
msg = msg+'\r'
msg = msg.encode('utf-8')
connection_with_server.send(msg)
received_message = connection_with_server.recv(1024)
print('received message: ', received_message.decode())
print('connection closed')
And server code
import socket
import select
def openEthernetConnection(host,port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
print("Server is now listening on port {}".format(port))
return(s)
if __name__ == '__main__':
protocole = 'ethernet'
encode_format = 'utf-8'
if protocole == 'ethernet':
# open ethernet connection
host = ''
port = 12800
mysocket = openEthernetConnection(host,port)
clients_connected = []
while True:
if protocole == 'ethernet':
# Check for new clients
new_connections, wlist, xlist = select.select([mysocket],
[], [], 0.05)
for connection in new_connections:
connexion_with_client, infos_connexion = connection.accept()
# On ajoute le socket connecté à la liste des clients
clients_connected.append(connexion_with_client)
# Listen the list of connected clients
# select return clients who must be read with recv
# wait 50ms
# select.select in a try loop if we want to raise an exception if no clients are connected
clients_to_read = []
try:
clients_to_read, wlist, xlist = select.select(clients_connected,
[], [], 0.05)
except select.error:
pass
else:
command = []
# Go through the clients list to be read
for client in clients_to_read:
received_command = client.recv(1024)
try:
received_command = received_command.decode(encode_format)
command = received_command.split()
print('command: ', command)
except UnicodeDecodeError:
return_message = 'E010'
pass
for client in clients_to_read:
return_message = '5/5'
client.sendall(return_message.encode(encode_format))
Thanks for your help !