Tech With Tim Logo
Go back

Creating the Server

Creating the Server

In this tutorial we will create the server for our game. The server is responsible for handling all of the different clients that are playing our game. It will store and send information to each of clients appropriately.

Finding The Server IP Address

For this tutorial we will be creating a server on our local network. This means that people outside our network will not be able to connect.

To find the address that you should use in the server variable simply open cmd > type "ipconfig" > copy the IPV4 Address. Do this on whatever machine will be running the server script. ip.png

Server Code

import socket
from _thread import *
import sys

server = "IPV4 ADDRESS HERE"
port = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((server, port))
except socket.error as e:
    str(e)

s.listen(2)
print("Waiting for a connection, Server Started")


def threaded_client(conn):
    conn.send(str.encode("Connected"))
    reply = ""
    while True:
        try:
            data = conn.recv(2048)
            reply = data.decode("utf-8")

            if not data:
                print("Disconnected")
                break
            else:
                print("Received: ", reply)
                print("Sending : ", reply)

            conn.sendall(str.encode(reply))
        except:
            break

    print("Lost connection")
    conn.close()


while True:
    conn, addr = s.accept()
    print("Connected to:", addr)

    start_new_thread(threaded_client, (conn,))
Design & Development by Ibezio Logo