今天学习了一个python 网络编程,感觉比较简单,也就是基本那几步,create--bind---listen -->receive/send---->close.
还学习一个Tcp版 Server编程框架,可以支持多个socket连接的那种。感觉也还可以。其中最简单的框架为TCPServer+BaseRequestHandler:。简单的例子如下:
import SocketServer #本程序可以支持多个客户端连接请求 class MyRequestHandler(SocketServer.BaseRequestHandler): #self.request其实就是一个socket def handle(self): addr =self.request.getpeername() print "got connection from",addr while True: #当客户端主动断开连接时,self.recv(1024)会抛出异常 try: #read 1024 byte each time ,and remove empty letter including(space tab \r \n) data = self.request.recv(1024).strip() if not data: break print "receive from(%s):%s" %(self.client_address,data) self.request.sendall(data.upper()) except: traceback.print_exc() break self.request.close() addr=('127.0.0.1',8000) server =SocketServer.ThreadingTCPServer(addr,MyRequestHandler) server.serve_forever() #只是反复调用handle_request() #server.handle_request() #一个一个的处理链接请求。
客户端为:
# *_* coding=gb2312 *-* import time import sys import logging from socket import * host = "127.0.0.1" port = 8000 def Test(): global host,port bufsize=1024 #print "Hello world" #logging.warn("there are some error") client =socket(AF_INET,SOCK_STREAM) client.connect((host,port)) while True: data =raw_input("Please input sending data:") if not data or data =="exit": break client.send("%s" % data) data =client.recv(bufsize) if not data: break print data.strip() client.close() if __name__ == '__main__': Test()
原文地址:http://blog.csdn.net/smartfox80/article/details/43372419