-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer2.py
91 lines (69 loc) · 2.47 KB
/
Server2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import pickle
import socket
from _thread import *
from Game.Player2.ServerGame2 import ServerGame2
"""
The server object. It will have methods to setup the server, start the server, and a method
to perform threaded actions on each connections. They will also try to broadcast
"""
class Server2:
def __init__(self):
self.server = "192.168.1.241"
self.port = 5555
self.idCount = 0
self.games = {}
self.connections = {}
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.setup()
self.startup()
def setup(self):
try:
self.server_socket.bind((self.server, self.port))
except socket.error as e:
str(e)
def startup(self):
self.server_socket.listen(2)
print("Waiting for a connection, Server Started.")
while True:
conn, addr = self.server_socket.accept()
print("Connected to: ", addr)
self.idCount += 1
player = 1
game_id = (self.idCount - 1) // 2
if self.idCount % 2 == 1:
self.games[game_id] = ServerGame2(game_id)
self.connections[game_id] = [conn]
print("Creating a new game...")
else:
self.games[game_id].set_ready(True)
player = 2
self.connections[game_id].append(conn)
start_new_thread(self.threaded_client, (conn, player, game_id))
def threaded_client(self, conn, player, game_id):
conn.send(str.encode(str(player)))
while True:
try:
data = conn.recv(2048 * 4).decode()
if game_id in self.games:
game = self.games[game_id]
if not data:
print("Disconnected.")
break
elif data == "get":
conn.send(pickle.dumps([game, player]))
else:
for client in self.connections[game_id]:
if conn != client:
client.send(str.encode(data))
conn.sendall(pickle.dumps([game, player]))
except:
break
print("Lost connection.")
try:
del self.games[game_id]
print("Closing Game", game_id)
except:
pass
self.idCount -= 1
conn.close()
server = Server2()