How to make the server available to local clients

I am working on a multi-player game in python that uses a socket library for its network. The game will support playback on the local network. One player will configure the server, while other players on the local network will be able to join the game.

To implement this, I need an easy way for players to open a list of available servers (players should not be expected to enter IP addresses!). My preferred solution will only use the python socket library (and possibly other parts of the standard library).

I am looking for client and server code:

  • client: broadcasts its request for games for all computers listening to a specific port on the local network.

  • server (s): responds to the client with its availability

NEXT RESPONSE Following Hans' recommendations in his answer below, a UDP socket can be used to respond to broadcast requests from a client.

Server:

#UDP server responds to broadcast packets #you can have more than one instance of these running import socket address = ('', 54545) server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) server_socket.bind(address) while True: print "Listening" recv_data, addr = server_socket.recvfrom(2048) print addr,':',recv_data server_socket.sendto("*"+recv_data, addr) 

Customer:

 #UDP client broadcasts to server(s) import socket address = ('<broadcast>', 54545) client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) data = "Request" client_socket.sendto(data, address) while True: recv_data, addr = client_socket.recvfrom(2048) print addr,recv_data 

Are there other convincing ways to solve this detection problem?

+6
source share
1 answer

You can try UDP translation. You can, for example, send a broadcast from a client. Then the server must send a response with its address so that the client can use a regular connection.

See sample code here: http://wiki.python.org/moin/UdpCommunication

+3
source

Source: https://habr.com/ru/post/951123/


All Articles