-
Notifications
You must be signed in to change notification settings - Fork 1
/
Server.py
182 lines (116 loc) · 5.61 KB
/
Server.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import PySimpleGUI as sg
import socket
import threading
server = socket.socket()
sg.theme('DefaultNoMoreNagging')
# All the stuff inside your window.
layout = [ [sg.Text('Port Number: '),sg.InputText(size=(30,2),key='-PORT-'),sg.Button('Start Listening',key='-LISTEN-', disabled=False)],
[sg.Text(key='-ERROR-')],
[sg.Multiline(size=(60,10), key='-MSG_BOX-',disabled=True)],
[sg.Multiline(key='-SERVERINPUT-',enable_events=True), sg.Button('Send',key='-SEND-',disabled=True)],
[sg.Button('Close Server',disabled=True,key='-CLOSE-')]
]
# Create the Window
window = sg.Window('Server', layout,finalize=True)
messages = [] #for appending messages on the console.
clients = [] #saving all connected clients.
#This thread is responsible for retriving data from a client and passing it down to other connected clients.
def new_client(clientSocket,clientAddress):
while True:
try:
clientData = clientSocket.recv(2048).decode('utf-8')
except socket.error as e:
window['-ERROR-'].update("Client_Thread: "+str(e))
clientSocket.close()
clients.remove(clientSocket)
break
# if dissconected message recived from the client, then close that socket.
if clientData == 'Disconnected':
message = "Client: "+str(clientAddress)+"Disconnected!"
messages.append(message)
window['-MSG_BOX-'].update('\n'.join(messages))
clients.remove(clientSocket)
#clientSocket.close()
clientData = str(clientAddress) + ': ' + clientData
message = "MESSAGE:"+clientData
messages.append(message)
window['-MSG_BOX-'].update('\n'.join(messages))
#all other clients except the sending client is being sent the message
for otherclients in clients:
if otherclients != clientSocket:
otherclients.sendall(clientData.encode())
#Server Thread is responsible for accepting connections from the client and creates a client thread for each connected client.
def server_thread():
while True:
try:
server.listen(10)
clientSocket,clientAddress = server.accept()
clients.append(clientSocket)
message = "Client: "+str(clientAddress)+"Connected!"
messages.append(message)
window['-MSG_BOX-'].update('\n'.join(messages))
serverToClientMessage = "***You are Connected to the server**"
clientSocket.sendall(serverToClientMessage.encode())
client_thread = threading.Thread(target=new_client, args=(clientSocket,clientAddress)) #client thread being created
client_thread.start()
except socket.error as e:
window['-ERROR-'].update("Server_Thread: "+str(e))
break
# Event Loop to process "events" and get the "values" of the inputs
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
if event=='-SERVERINPUT-':
if values['-SERVERINPUT-'] == '' or values['-SERVERINPUT-'] == ' ' or None:
window['-SEND-'].update(disabled=True)
else:
window['-SEND-'].update(disabled=False)
if event == '-LISTEN-':
if len(clients)!=0:
clients = []
try:
server = socket.socket()
if int(values['-PORT-']) >=0 and int(values['-PORT-']) <=65536:
window['-ERROR-'].update(" ")
server.bind(('localhost',int(values['-PORT-']))) #SERVER BIND
print(server)
serverThread = threading.Thread(target=server_thread, args=())
serverThread.start()
message = "Server is now listening on Port: "+values['-PORT-']
messages.append(message)
window['-MSG_BOX-'].update('\n'.join(messages))
window['-LISTEN-'].update(disabled=True)
window['-CLOSE-'].update(disabled=False)
else:
window['-ERROR-'].update("Port Number out of Range!")
except socket.error as e:
#new_client.join()
window['-ERROR-'].update('LISTEN: '+str(e))
if event == '-SEND-': #when server sends message, it is sent to all clients.
try:
messages.append('You: '+values['-SERVERINPUT-'])
window['-MSG_BOX-'].update('\n'.join(messages))
window['-SERVERINPUT-'].update('')
window['-SEND-'].update(disabled=True)
for c in clients:
data = 'Server: ' + ' ' + values['-SERVERINPUT-']
c.sendall(data.encode())
except socket.error as e:
window['-ERROR-'].update("-SEND-: "+str(e))
if event == '-CLOSE-': #When server closes the sever, it alerts all clients and disconnects all clients.
try:
window['-LISTEN-'].update(disabled=False)
window['-CLOSE-'].update(disabled=True)
messages.append('Server Shutdown.')
window['-MSG_BOX-'].update('\n'.join(messages)) #add server message on the messagebox
for c in clients:
data = '***SERVER SHUTDOWN***'
c.sendall(data.encode())
c.close()
server.close()
except socket.error as e:
window['-MSG_BOX-'].update('CLOSE: '+str(e)) #add server message on the messagebox
#server.close()
server.close()
window.close()