sinθ
sinθ

Reputation: 11493

Python Game Server

I'm completely lost trying to create a UDP server/client for my game in python. I'm new to the language and only have limited experience with networking. Right now, the server runs, but doesn't seem to be getting any messages from the client.

Server:

class GameServer:
    class GameServerUDPHandler(socketserver.BaseRequestHandler):
        def handle(self):
            data = self.request[0].strip()
            socket = self.request[1]
            print("{} wrote:".format(self.client_address[0]))
            print(data)
            socket.sendto(data.upper(), self.client_address)

    def __init__(self, port):
        self.server = socketserver.UDPServer(("localhost", port), self.GameServerUDPHandler)

    def start_server(self):
        self.server.serve_forever(

Client:

import socket
import sys

class GameClient:
    def __init__(self, port, host):
        self.port = port
        self.host = host
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    def register(self):
        self.socket.sendto(bytes("register\n", "utf-8"), (self.host, self.port))
        self.numberID = int(self.socket.recv(1024))
        print("Received:   {}".format(self.numberID))

-Main/Start of program

import gameserver
import gameclient

if __name__ == "__main__":
    server = gameserver.GameServer(1300)
    server.start_server()
    client = gameclient.GameClient(1300, "localhost")
    client.register()

NOTE: I'm most likely to multiple things wrong and may be violating several best practices in the language. I really have no clue.

Upvotes: 2

Views: 4233

Answers (2)

Guy Sirton
Guy Sirton

Reputation: 8401

Seems like this library isn't asynchronous so your first call to serve_forever will not return and your client never gets started. You can create a new thread to launch the server on or split your client and server into seperate processes.

Upvotes: 1

Thomas
Thomas

Reputation: 181745

The problem is that some of these calls are blocking. In particular, the serve_forever() method will run forever, so you need to put that on a separate thread if you want the rest of your program to continue:

import threading
if __name__ == "__main__":
    server = GameServer(1300)
    server_thread = threading.Thread(target=lambda: server.start_server())
    server_thread.start()

    time.sleep(1) # Give it time to start up; not production quality code of course

    client = GameClient(1300, "localhost")
    client.register()

socket.recv() is also a blocking call but that might be okay in this case.

Upvotes: 3

Related Questions