Home >Backend Development >Python Tutorial >Python警察与小偷的实现之一客户端与服务端通信实例

Python警察与小偷的实现之一客户端与服务端通信实例

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-16 08:41:141343browse

本文实例讲述了Python警察与小偷的实现之一客户端与服务端通信,分享给大家供大家参考。具体方法分析如下:

该实例来源于ISCC 2012 破解关第四题
目的是通过逆向police,实现一个thief,能够与police进行通信

实际上就是一个RSA加密通信的例子,我们通过自己编写客户端和服务端来实现上面的thief和police的功能.

要通信,这们这次先通过python写出可以进行网络连接的客户端与服务端.

服务端代码如下:

#!/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() 

客户端代码如下:

#!/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('%s\r\n' % data)  
  data = tcpCliSock.recv(BUFSIZ)  
  if not data:  
    break  
  print data.strip()  
#tcpCliSock.close() 

这段代码可参考《python核心编程》

如果报python errno 10053错误,请确认下客户端的连接代码一定要在循环外
也就是:

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

要在while True的外面。

下次解决RSA加密的问题。

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn