I was working on a chess game and had it working but wanted to make one that would work using sockets in which I could play with my siblings using a different device but on the same network. Made a network module for the clients and a server.py file that would receive moves and forward them to the opponent. Long story short sending moves was working perfectly, but I hit a brick wall when receiving moves. Here is a minimum reproducable example:
SERVER.PY
import socket
from _thread import *
import sys
server = "192.168.0.189" # Update this with your server IP address
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
print(e)
s.listen(2)
print("Waiting")
connections = []
players = ["white", "black"] # Assign colors to players
def threaded_client(conn, player):
conn.send(players[player].encode()) # Send player color to the client
reply = ""
while True:
try:
data = conn.recv(2048)
reply = data.decode("utf-8")
if not data:
print("disconnected")
break
else:
print("Received: ", reply)
# Forward the move to the other client
for c in connections:
if c != conn:
c.sendall(data)
except socket.error as e:
print(e)
break
print("lost connection")
conn.close()
current_player = 0
while True:
conn, addr = s.accept()
print("connected to: ", addr)
connections.append(conn)
start_new_thread(threaded_client, (conn, current_player))
current_player += 1
client.py:
import pygame
from network import Network
width = 500
height = 500
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Client")
def redrawWindow(win):
win.fill((255,255,255))
pygame.display.update()
def main():
n = Network()
my_color = n.get_pos()
print(my_color)
run = True
clock = pygame.time.Clock()
turn = 'white'
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN and my_color == turn:
pos = pygame.mouse.get_pos()
pos_str = str(pos)
print("sent: ", pos_str)
n.send(pos_str)
turn = 'black' if turn == 'white' else 'white'
if my_color != turn:
opp_pos = None
opp_pos = n.receive()
if opp_pos is not None:
print(opp_pos)
redrawWindow(win)
main()
In this example opponents send their mouse pos upon clicking the left click button based on turns. I run 2 instances of client.py and on both its whites turn a color is assigned to both by the server upon joining and first client gets white and second gets black so at start 1st client is ready to send pos and 2nd should be ready to receive it but the secong just shows a black screen upon startup and just doesn’t respond. I assume that its endlessly waiting for servers msg and isnt abble to do any thing else but I am not able to find a work around or any other way to receive data.
I would really appereciate if someone could thoroughly guide me.
0