Sunday, May 19, 2024
HomeGame Developmentpygame - How to receive data on a Python socket only when...

pygame – How to receive data on a Python socket only when data is available?


I am writing an update to a game I have written in python, and I am currently adding server support. I can’t show you the main code (for the client), as it is hundreds of lines long. However, what I can do is show you this snippet of code from lines 34 to 47:

s = ""
serverMode = "noServer"
def getserver(server_ip,server_num):
    global s, serverMode
    try:
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.settimeout(2)
        s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        s.connect((server_ip,server_num))
        print "connected to " + str(server_ip)
        serverMode = "activeServer"
    except:
        easygui.msgbox("The server is not running or does not exist.")
        s = None

the ‘s’ variable is where the server socket is kept. the ‘serverMode’ holds the information on wether the game is connected to an active server or not, so that if so, it can be constantly checking for updates in the code. Here is the server code, which is significantly shorter than the main code:

import socket, signal

print "[SERVER INFO] hosted at " + str(socket.gethostname())
print "[SERVER INFO] loading server..."

def doStuff():
    pass

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
#socket.fork()
serversocket.bind((socket.gethostname(), 80))
serversocket.listen(5);

print "[SERVER INFO] server started."

clients = []

running = True
while running:

    (clientsocket, address) = serversocket.accept()
    if not [clientsocket, address] in clients: clients.append([clientsocket, address])
    data = clientsocket.recv(2048)
    if not data: pass
    elif data.startswith("[SERVER INFO]"): print data
    elif data == "disconnect":
        pass
    elif data.startswith("[BLOCK PLACEMENT]"):
        blocktype = data.split(' ')[1]
        loc = [data.split(' ')[2], data.split(' ')[3]]
        for client in clients:
            try: client.send(bytes("[BLOCK] " + str(loc[0]) + "," + str(loc[1]) + "," + blocktype))
            except: pass
    elif data.startswith("[CHAT MESSAGE]"):
        for client in clients:
            try: client.send(bytes(data))
            except: pass
    clientsocket.sendall(bytes("0,0,wood.png\n20,20,wood.png"))

serversocket.shutdown(0)
print "[SERVER INFO] server shutdown correctly."
raw_input()

As I mentioned, the client is constantly checking for server updates. It uses the recv function in sockets. So because of this, it runs extremely slow. I have looked at online tutorials on how to fix similar things, but nothing seems to work for me. Nevertheless, here is the code that checks for updates:

if serverMode == "activeServer":
    #s.setsocketopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        recvbuff = 100
        rx_bufftmp = s.recv(recvbuff)
        rx_bufftmplen = len(rx_bufftmp)
        recvbuff = max(recvbuff, rx_bufftmplen)
    except: data = False
    if not data == False and data.startswith('[BLOCK]'):
        blk = rx_bufftmp.split(' ')[1].split(',')
        blx = blk[1]
        bly = blk[2]
        bln = blk[0]
        bls.append(Block(bln, [int(blx), int(bly)]))

The code runs in the pygame mainloop. So, since I was not able to find any ways to optimize performance, may there be a way instead to only grab data if there is incoming data? Maybe also some other ways to optimize performance as well?

FYI:

I am running a 32 bit version of python 2.7 on a 64 bit installation of Windows 10.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments