每天一道python练习06 发表于 2017-08-18 | 字数统计 394 | 阅读时长 2 题目:建立一个简单的TCP客户端和服务器. 1.采用socket模块建立 Tcp服务器代码: 12345678910111213141516171819202122232425262728293031#!/usr/bin/env python# -*- coding:utf-8 -*-# create Ttstcyfrom socket import *from time import ctime'''一个简单的tcp服务器'''Host='127.0.0.1' Port=56478Buffer=1024add=(Host,Port)tcpSocket=socket(AF_INET,SOCK_STREAM) #建立socket套接字tcpSocket.bind(add) #绑定地址tcpSocket.listen(5) #接受最大连接数while True: print('waiting for connection......') tcpSocket,add=tcpSocket.accept() #接收客户端连接 print('connection from:' , add) while True: data=tcpSocket.recv(Buffer) if not data: break; tcpSocket.send('[%s] %s' % (ctime(),data)) #返回消息 tcpClient.close() #关闭当前客户端连接tcpSocket.close() Tcp客户端代码: 123456789101112131415161718192021222324252627282930#!/usr/bin/env python# -*- coding=utf-8 -*-# create Ttstcyfrom socket import *'''一个简单的TCP客户端'''Host='127.0.0.1'Port=56478Buffer=1024Add=(Host,Port)tcpClient=socket(AF_INET,SOCK_STREAM) #建立socket套接字tcpClient.connect(Add) #连接服务器while True: data= raw_input('> ') if not data: break; tcpClient.send(data) #向服务器发送数据 data=tcpClient.recv(Buffer) if not data: break; print datatcpClient.close() #关闭客户端连接 2.采用SocketServer创建 Tcp服务器代码: 123456789101112131415161718192021222324#!/usr/bin/env python# -*- coding=utf-8 -*-from SocketServer import *from time import ctime'''简单的SocketServer Tcp服务器'''Host='127.0.0.1'Port=15489Add=(Host,Port)class MyRequestHandler(StreamRequestHandler): #重写Handler方法 def handler(self): print 'connection from :',self.client_address self.wfile('[%s] %s' % (ctime(),self.rfile.readline())) #wfile来发送data,readline()用来获取客户端datetcpServ = TCPServer(Add,MyRequestHandler) print 'waiting for connection...'tcpServ.serve_forever() #无线循环请求 TCP客户端: 1234567891011121314151617181920212223242526#!/usr/bin/env python# -*- coding=utf-8 -*-from socket import *'''SocketServer 客户端'''Host='127.0.0.1'Port=15489Buffer=1024Add=(Host,Port)while True: tcpClient = socket(AF_INET,SOCK_STREAM) tcpClient.connect(Add) data= raw_input('>') if not data: break tcpClient.send('%s\n' % data) data= tcpClient.recv(Buffer) if not data: break print data tcpClient.close()