-
Notifications
You must be signed in to change notification settings - Fork 29
/
server.py
64 lines (53 loc) · 2.45 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
from concurrent import futures
import grpc
import time
import proto.chat_pb2 as chat
import proto.chat_pb2_grpc as rpc
class ChatServer(rpc.ChatServerServicer): # inheriting here from the protobuf rpc file which is generated
def __init__(self):
# List with all the chat history
self.chats = []
# The stream which will be used to send new messages to clients
def ChatStream(self, request_iterator, context):
"""
This is a response-stream type call. This means the server can keep sending messages
Every client opens this connection and waits for server to send new messages
:param request_iterator:
:param context:
:return:
"""
lastindex = 0
# For every client a infinite loop starts (in gRPC's own managed thread)
while True:
# Check if there are any new messages
while len(self.chats) > lastindex:
n = self.chats[lastindex]
lastindex += 1
yield n
def SendNote(self, request: chat.Note, context):
"""
This method is called when a clients sends a Note to the server.
:param request:
:param context:
:return:
"""
# this is only for the server console
print("[{}] {}".format(request.name, request.message))
# Add it to the chat history
self.chats.append(request)
return chat.Empty() # something needs to be returned required by protobuf language, we just return empty msg
if __name__ == '__main__':
port = 11912 # a random port for the server to run on
# the workers is like the amount of threads that can be opened at the same time, when there are 10 clients connected
# then no more clients able to connect to the server.
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) # create a gRPC server
rpc.add_ChatServerServicer_to_server(ChatServer(), server) # register the server to gRPC
# gRPC basically manages all the threading and server responding logic, which is perfect!
print('Starting server. Listening...')
server.add_insecure_port('[::]:' + str(port))
server.start()
# Server starts in background (in another thread) so keep waiting
# if we don't wait here the main thread will end, which will end all the child threads, and thus the threads
# from the server won't continue to work and stop the server
while True:
time.sleep(64 * 64 * 100)