Python-socket realizes communication between servers

Keywords: Python JSON Database socket Programming

Now we need to do a distributed curriculum design (simple games), which is completed by three groups of people.

I need to design a login registration server to receive user login registration message requests from gateway server (message middleware), then generate a message to access the database server, send it to the database server, receive and process its return information, and send the login registration results to the gateway server. (Very simple function)

My idea is that the main thread of the login registry server runs all the time, monitoring whether there are connection requests from the gateway server. Whenever a connection request is received, a new sub-thread is created to process the message request from the gateway server, and generate the request message to access the database, which is sent to the database server. Then the returned database operation information is received. After processing, the sub-thread sends the login registration result to the gateway server.

Programming language: Python

Network communication mode: tcp (socket)

Data exchange format: json

Flow chart:

The code is as follows:

 1 Server.py
 2 
 3 # -*- coding: UTF-8 -*-
 4 import socket
 5 import datetime
 6 import time
 7 import json
 8 
 9 class Server(object):
10     """Server Side"""
11     
12     def __init__(self):
13         self.host = '219.224.167.162'
14         self.port = 6999
15         Arr=(self.host,self.port)
16         self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
17         self.s.bind(Arr)
18         self.s.listen(5) #Maximum number of connections that an operating system can suspend
19         
20     def ReceiveMSG(self, threadname, sk_conn):
21         try:
22             msg_conn = sk_conn.recv(1024).decode()
23             data_conn= json.loads(msg_conn)
24             print(data_conn)
25             #Accessing database server
26             sk_db = socket.socket()        # Establish socket object
27             host = '219.224.167.250'    # Get the host name of the database server
28             port = 9999                 # Setting Port Number
29             sk_db.connect((host, port))
30             #Analytical Client Logon or register
31             if data_conn[0]['OP']=='login':
32                 print('  -[Login:',data_conn)
33                 data=[{'OP':'login','username':'%s'%(data_conn[0]['username'])}]
34                 msg=json.dumps(data)
35                 sk_db.send(msg.encode())
36                 print('  -The database server returns:')
37                 while True:
38                     msg=sk_db.recv(1024).decode()
39                     print('    ',msg)
40                     if msg=='Close!':
41                         sk_db.close()
42                         break
43                     if msg=='Welcome!':
44                         continue
45                     else:
46                         data=json.loads(msg)
47                         sk_db.send(b'exit')
48                         if data[0]['password']=='None':
49                             data=[{'code':1,'info':'Failed for error username!'}]
50                         elif data[0]['password']!=data_conn[0]['password']:
51                             data=[{'code':2,'info':'Failed for error password!'}]
52                         else:
53                             data=[{'code':3,'info':'success!'}]
54                  
55                 ##Return information to client
56                 #data=[{'code':3,'info':'success!'}]#
57                 msg=json.dumps(data)
58                 print('    Return client information: ',msg)
59                 sk_conn.send(msg.encode())
60                 sk_conn.close()
61             else:
62                 print('  -[Registration]:',data_conn)
63                 data=data_conn
64                 msg=json.dumps(data)
65                 sk_db.send(msg.encode())
66                 print('  -The database server returns:')
67                 while True:
68                     msg=sk_db.recv(1024).decode()
69                     print('    ',msg)
70                     if msg=='Close!':
71                         sk_db.close()
72                         break
73                     if msg=='Welcome!':
74                         continue
75                     else:
76                         data=json.loads(msg)
77                         sk_db.send(b'exit')
78                         if data[0]['msg']=='success':
79                             data=[{'code':4,'info':'success'}]
80                         else:
81                             data=[{'code':5,'info':'fail'}]
82                 #data=[{'code':4,'info':'success'}]#
83                 #Return information to client
84                 msg=json.dumps(data)
85                 print('    Return client information: ',msg)
86                 sk_conn.send(msg.encode())
87                 sk_conn.close()
88         except BaseException:
89              print('An unknow error occurred.')
90             
91     def __delattr__(self):
92         self.sock.close()
93         self.s.close()

 

 1 LoginRegisterServer.py
 2 Main thread
 3 
 4 # -*- coding: UTF-8 -*-
 5 import _thread
 6 import time
 7 import json
 8 from Server import Server
 9 from Client import Client
10 
11 print('The server has been started and started to provide the login registration service...\n')
12 server=Server()
13 
14 while True:
15     sk_conn,addr = server.s.accept()
16     print('\n Request link user information:', addr)
17     
18     try:
19         _thread.start_new_thread( server.ReceiveMSG, ("Thread: deal with request.", sk_conn) )
20     except:
21         print("Error: unable to start thread")

Posted by Irvin Amoraal on Thu, 11 Apr 2019 10:06:32 -0700