代码语言:javascript复制
//服务器端代码
from socket import *
from time import ctime
host='localhost'
port=3330
bufsize = 1024
addr = (host,port)
tcpser = socket(AF_INET,SOCK_STREAM)
tcpser.bind(addr)
tcpser.listen(5)
while True:
print('waiting for connetion....')
tcpCliSock,ADDR = tcpser.accept()
print('...connection from:',ADDR)
while True:
data = tcpCliSock.recv(bufsize)
if not data:
break
tcpCliSock.send(('[%s]%s'%(ctime(),data)).encode())
tcpCliSock.close()
tcpser.close()
代码语言:javascript复制//客户端代码
from socket import *
host='localhost'
port=3330
bufsize = 1024
addr = (host,port)
tcpser = socket(AF_INET,SOCK_STREAM)
tcpser.connect(addr)
while True:
data = input('>')
if not data:
break
tcpser.send(data.encode())
data = tcpser.recv(bufsize).decode()
if not data:
break
print(data)
tcpser.close()
以上代码为python核心编程(第三版)网络编程一节代码,其中一些错误已经被我修改可正常运行