Skip to content Skip to sidebar Skip to footer

Python Sockets For A N-players Game

I'm a python(3) begginer and I want to do a n-players game. This players will connect to the server to play. I'm practicing with an easy example I've found, but when I run it, it t

Solution 1:

save both files in the same directory and open 2 terminals there

run server.py first (it should just wait for a connection) (if you already have server.py running somewhere this will result in an error, only one instance of server.py may be running on a given computer/port at a time )

then run client.py (while server.py is running in first terminal)

client.py

importsockets= socket.socket() 
s.connect((socket.gethostname(), 9999))

while True:
    message = input("> ")
    s.send(message)
    ifmessage== "quit":
        breakprint("bye")

s.close()

server.py

import socket

#Server

s = socket.socket() 
s.bind((socket.gethostname(), 9999))
s.listen(1)

sc, addr = s.accept()

whileTrue:
    received = sc.recv(1024)
    if received == "quit":
        breakprint ("Received:", received)
    sc.send(received)

print ("bye")

sc.close()
s.close()

Solution 2:

i think your problem is in your adress binding. instead of s.bind((socket.gethostname(), 9999)), it should be s.bind((socket.gethostname(socket.gethostbyname()), 9999))

Post a Comment for "Python Sockets For A N-players Game"