One of the implementations of Python police and thieves is a client server communication instance

  • 2020-04-02 14:15:12
  • OfStack

This article illustrates one of the implementations of Python police and thieves: client and server communication. Specific methods are analyzed as follows:

This example comes from ISCC 2012 to solve the fourth problem
The goal is to achieve a thief through reverse police, able to communicate with the police

This is actually an example of RSA encrypted communication, where we wrote our own client and server side to implement the above functions of thief and police.

To communicate, we first write out the client and the server that can connect to the network through python.

The server code is as follows:


#!/usr/bin/env python  
import SocketServer  
from time import ctime  
HOST = '127.0.0.1' 
PORT = 2012  
ADDR = (HOST, PORT)  
class MyRequestHandler(SocketServer.BaseRequestHandler): 
    def handle(self): 
        print '...connected from...', self.client_address 
        while True:  
            self.request.sendall('[%s] %s' % (ctime(),self.request.recv(1024))) 
 
 
tcpServ = SocketServer.ThreadingTCPServer(ADDR, MyRequestHandler)  
print 'waiting for connection...'  
tcpServ.serve_forever() 

The client code is as follows:


#!/usr/bin/env python  
from socket import *  
HOST = '127.0.0.1'  
PORT = 2012  
BUFSIZ = 1024  
ADDR = (HOST, PORT)  
 
tcpCliSock = socket(AF_INET, SOCK_STREAM)  
tcpCliSock.connect(ADDR)  
while True:  
  data = raw_input('>>>>>>>>>>>>')  
  if not data:  
    break  
  tcpCliSock.send('%srn' % data)  
  data = tcpCliSock.recv(BUFSIZ)  
  if not data:  
    break  
  print data.strip()  
#tcpCliSock.close() 

This code can be referred to (link: #)

If the python errno 10053 error is reported, make sure the client's connection code is outside the loop
That is:


tcpCliSock = socket(AF_INET, SOCK_STREAM)  
tcpCliSock.connect(ADDR)  

Outside of while True.

Solve the RSA encryption problem next time.

I hope this article has helped you with your Python programming.


Related articles: