Reputation: 2913
I've written a python chess game that I'd like to make playable by two people on two different computers. Without using external libraries, my first thought was to try to adapt code for a simple chat server/client to allow the game to communicate moves to both users. From my research, it seems the following code is pretty standard:
# client
from socket import *
PORT = 8000
s = socket(AF_INET, SOCK_STREAM)
s.connect(('', PORT))
while True:
msg = raw_input('>> ')
s.send(msg)
reply = s.recv(1024)
if reply:
print '<< ' + str(reply)
s.close()
#server
from socket import *
HOST = ''
PORT = 8000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2)
conn, address = s.accept()
while True:
print 'got a connection'
data = conn.recv(1024)
if data:
print 'we got it'
conn.sendall(data)
s.close()
My thinking is that one player (the host who invites the other player to the game), initiates the game and the server. The client then moves, sends the move to the server, and the change is reflected on the UI.
However, the infinite loops above that listen for messages/responses are giving me trouble: clearly, no other code can execute. I'd rather have the connection between client and server be in the background, or even better make use of the infinite loop already used by the UI to listen to events.
My question: is it possible to use Tkinter's mainloop
to act as an infinite loop to listen for incoming data and replies? Or, would it be better to run the server and the client as subprocesses. I guess what I'd really like is to treat the listening/receiving for moves as events: when a move is made, a message is sent, and it is "handled" by the client.
Note: this is the first time I've ever used the socket library -- it would be great if any answers could respect my relative naiveté with the topic.
Edit: I think what I might need is asynchat, but I would very much appreciate understanding how this code might be adapted.
Final remarks: gordosac's answer provided some great ideas to search. I ended up finding exactly what I need here
Upvotes: 1
Views: 2972
Reputation: 26
Take a look at this question on SO:
How to use threading in Python?
You would do something like this for the client:
import threading
import os
import time
# this function meant to be started in a separate thread
get_raw_input_and_send():
#put while loop here
if __name__ == "__main__":
t = threading.Thread(target=get_raw_input_and_send)
t.daemon = True
t.start()
while True:
if not t.isAlive():
os.sys.exit(-1)
time.sleep(5)
Then on the server side do the equivalent but with the while loop from the server code
Upvotes: 1