服务端:
# -*- coding:utf-8 -*- """ created on 2019-07-09 author swen file read/write 网络编程:服务器TCP套接字创建 """ from socket import * from time import ctime addr=('',23356) BUFSIZE=1024 tcpSerSoc=socket() tcpSerSoc.bind(addr) tcpSerSoc.listen(5) while True: #TCP等待的是一个连接进来,UDP等到四信息直接进来 print '...waiting connect...:' tcpCltSoc,addr=tcpSerSoc.accept() print '...connect from...:',addr while True: data=tcpCltSoc.recv(BUFSIZE) if not data: break tcpCltSoc.send('[%s]%s'%(ctime(),data)) tcpCltSoc.close() tcpSerSoc.close()客户端:
# -*- coding:utf-8 -*- """ created on 2019-07-09 author swen file read/write 网络编程:客户端TCP套接字创建 """ from socket import * addr=('localhost',23356) BUFSIZE=1024 tcpCltSoc=socket() tcpCltSoc.connect(addr) while True: data=raw_input('>') if not data: break tcpCltSoc.send(data) data=tcpCltSoc.recv(BUFSIZE) if not data: break print data tcpCltSoc.close()[参考]Python核心编程(第二版).pdf