Reputation: 65
I've been having trouble sending data between two pi's using socket.send and socket.recv commands in python. I've followed an example on YouTube to help get the code started but whenever I try to send other types of data from the server to the client, the server stops and the client receives an empty value.
Server:
import socket
import time
host = '192.168.10.100'
port = 9988
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind complete.")
return s
def setupConnection():
s.listen(1) # Allows one connection at a time.
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def dataTransfer(conn):
while True:
data = conn.recv(1024) # receive the data
data = data.decode('utf-8')
if data == 'kill':
print("Server is shutting down.")
s.close()
break
elif data == 'test':
reply = 1
else:
reply = 'Unknown Command'
conn.sendall(reply)
conn.close()
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
break
Client:
import socket
from time import sleep
host = '192.168.10.100'
port = 9988
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
while True:
command = input("Enter command: ")
if command == 'KILL':
s.send(str.encode(command))
break
s.send(str.encode(command))
reply = s.recv(1024)
print(reply)
s.close()
When I run the 'kill' command it works normally:
But when I try to run 'test', the server script seems to close and the client seems to receive an empty value instead of 1.
After looking around it looks like I may be running into blocking/non-blocking issues or the socket.send/socket.recv commands aren't transferring the correct types of data. Perhaps I might have some other errors?
Upvotes: 2
Views: 3830
Reputation: 218
When the data=="test"
condition is hit, you're assigning your reply
to an integer value. socket.sendall
takes a string
argument. Try "1"
.
As a suggestion, this would be a good opportunity to use pdb to debug if you're not familiar with it. Simply import pdb
and wherever you want the program to pause (e.g. in the server's if block where data=="test"
), then simply have a statement pdb.set_trace()
and it will open an interactive terminal if the message is being received properly.
Upvotes: 1