啊峰哥

1.3用socketserver创建服务器

socket服务器代码

# -*- coding: utf-8 -*-
import
socketserver,time myHost = '' myPort = 50007 def now(): #返回一个时间 return time.ctime(time.time()) class MyClientHandler(socketserver.BaseRequestHandler): def handle(self): #处理每一个连接的用户 print(self.client_address,now()) #打印该用户地址 time.sleep(5) #模拟一个运行 while True: #self.reqeust指的是用户 data = self.request.recv(1024) # 从客户端接受信息 if not data: break reply = 'Ech0=>%s at %s'%(data,now()) self.request.send(reply.encode()) #发送信息给客户端 self.request.close() #创建线程,让服务器一直运行下去 myaddr = (myHost,myPort) server = socketserver.ThreadingTCPServer(myaddr,MyClientHandler) server.serve_forever()

socket客户端测试代码

# -*- coding: utf-8 -*-
from
socket import * serverHost = 'localhost' serverPort = 50007 while True: messages = [input('输入').encode()] #输入信息,并设置编码, 可设置b''或者str.encode() socketobj = socket(AF_INET, SOCK_STREAM) # 创建TCP对象 socketobj.connect((serverHost, serverPort)) # 连接端口 for line in messages: socketobj.send(line) data = socketobj.recv(1024) # 从服务器接受信息 print('Client received:', data.decode()) #打印信息,解码打印,str.decode() socketobj.close()

 

posted on 2017-09-23 16:52  啊峰哥  阅读(201)  评论(0编辑  收藏  举报

导航