Answer the question
In order to leave comments, you need to log in
Determining client address in socketserver?
I am writing a server code for a game of checkers. Here I have a new process created every time for a new client. But since in the game we send messages, and in response to a player’s request, both to him and his opponent, I decided to remember his ip address in the player’s object so that later I could send messages to him (if his opponent is like it). How can we in the following code, when creating a new process with a client, find out its ip-address?
import pickle
import socket
import socketserver
import threading
import time
class Player:
def __init__(self, id, name, ip_adress):
self.id = id
self.name = name
#состояние 1 - прошел авторизацию но еще не играет, состояние 2 - еще не играет и ждет появление партнера по игре, состояние 3 - в игре
self.state=1
#игровой цвет - нужен для игры
self.color=None
self.ip=ip_adress
#список всех авторизированных игроков
list_of_player=[]
#обработчик запросов
class TCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
encoding = "utf-8"
#инфа что мы получили
data = self.request.recv(1024)
# Дальше мы обрабатываем данные, которые пришли
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
if __name__ == "__main__":
#адрес и порт нашего сервера
HOST, PORT = "localhost", 80
server = ThreadedTCPServer((HOST, PORT), TCPRequestHandler)
# ip, port = server.server_address
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = False
server_thread.start()
#чтобы сервер закрылся только при исключении, например прерывании с клавиатуры
while True:
try:
time.sleep(1)
except:
break
server.shutdown()
server.server_close()
Answer the question
In order to leave comments, you need to log in
I will assume that self.client_address
in the request handler.
RequestHandler.handle()https://docs.python.org/3.4/library/socketserver.h...
This function must do all the work required to service a request. The default implementation does nothing. Several instance attributes are available to it; the request is available as self.request; the client address as self.client_address; and the server instance as self.server, in case it needs access to per-server information.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question