This repository has been archived on 2020-03-29. You can view files and clone it, but cannot push or open issues or pull requests.
sampy_archive/objects/server.py
2018-09-26 08:41:50 +02:00

56 lines
1.3 KiB
Python

import socket
import select
from threading import Thread
from .client import Client
class Server(Thread):
BUFF_SIZE = 65535
def __init__(self, host, port):
super(Server, self).__init__()
self.daemon = True
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((self.host, self.port))
self.socket.setblocking(0)
self.clients = {}
def run(self):
# Main server loop
while True:
(incomming, _, _) = select.select(
[self.socket],
[],
[], 1)
if incomming:
data, addr = self.socket.recvfrom(self.BUFF_SIZE)
if addr in self.clients:
self.clients[addr].handle_data(data)
else:
try:
self.clients[addr] = Client(self, addr)
print("[Server] Accepted connection from {}:{}".format(addr[0], addr[1]))
self.clients[addr].handle_data(data)
except socket.error:
try:
self.socket.close()
except:
pass
print("[Server] Something went very wrong...")
exit()
clients = [x for x in self.clients.values()
if x.write_buffer_size() > 0]
for client in clients:
client.write_socket()
"""for c in self.clients.values():
print(c.__writebuffer)"""