Jump to content

Socket Communication With Python

Silverwolf_7
Go to solution Solved by Silverwolf_7,

I have answered my own question.

In the sever:

conn, addr = s.accept()

needs to be placed within the while loop.

I am trying to send messages from a client to a server using sockets. I have sent data however I would like the sever to listen constantly for data and print out each message as it comes in. The code works for the first message however for some reason all subsequent messages are not read. It's almost as if conn.recv(BUFFER_SIZE) is not blocking.

Server code:

import socket, time

TCP_IP = 'localhost' # this IP of the Raspberry Pi or the device receiving messages
TCP_PORT = 40000
BUFFER_SIZE = 64 #can lower for faster response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
conn.setblocking(True)
print ('Connection address:', addr)
count = 0
while True:
    robotMsg = conn.recv(BUFFER_SIZE)
    print('Recv message')
    if not robotMsg:
        print('Nothing read')
        count = count + 1
        time.sleep(1)
        if count > 5:
            conn.close()
            break  
    else:    
        robotMsg = robotMsg.decode('utf-8')
        print(robotMsg)

        if robotMsg == 'start':
            print('starting data recording')
        elif robotMsg == 'resume':
            print('resuming last file')
        elif robotMsg == '1_data':
            print('reading 1')
        elif robotMsg == '2_data':
            print('reading 2')
        elif robotMsg == 'exit':
            print('closing server')
            break
        else:
            print('unknown command')
        time.sleep(1)   
    
conn.close()

Client code:

import socket, time

TCP_IP = 'localhost' # this IP of the RaspberryPi or the device receiving messages.
TCP_PORT = 40000
BUFFER_SIZE = 64
MESSAGE = 'start'
count = 1

while count < 10:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, TCP_PORT))
    s.send(MESSAGE.encode('utf-8')) #.encode needed to send bytes
    print('Sent Message: ', MESSAGE)
    count = count + 1
    time.sleep(3)

print ('end')
exit = 'exit'
s.send(exit.encode('utf-8'))
s.close()

 

Link to comment
Share on other sites

Link to post
Share on other sites

I have answered my own question.

In the sever:

conn, addr = s.accept()

needs to be placed within the while loop.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×