Python3学习(六):使用socket实现TCP协议的简单服务器和客户端
程序员文章站
2022-06-06 16:08:25
...
服务器端的server.py内容如下:
#coding=utf-8
#创建TCP服务器
from socket import *
from time import ctime
HOST='10.0.64.60' #这个是我的服务器ip,根据情况改动
PORT=9090 #我的端口号
BUFSIZ=1024
ADDR=(HOST,PORT)
tcpSerSock=socket(AF_INET,SOCK_STREAM) #创服务器套接字
tcpSerSock.bind(ADDR) #套接字与地址绑定
tcpSerSock.listen(5) #监听连接,传入连接请求的最大数,一般为5就可以了
while True:
print('waiting for connection...')
tcpCliSock,addr =tcpSerSock.accept()
print('...connected from:',addr)
while True:
stock_codes = tcpCliSock.recv(BUFSIZ).decode() #收到的客户端的数据需要解码(python3特性)
print('stock_codes = ',stock_codes) #传入参数stock_codes
if not stock_codes:
break
tcpCliSock.send(('[%s] %s' %(ctime(),stock_codes)).encode()) #发送给客户端的数据需要编码(python3特性)
after_close_simulation = tcpCliSock.recv(BUFSIZ).decode() #收到的客户端的数据需要解码(python3特性)
print('after_close_simulation = ',after_close_simulation) #传入参数after_close_simulation
if not after_close_simulation:
break
tcpCliSock.send(('[%s] %s' %(ctime(),after_close_simulation)).encode()) #发送给客户端的数据需要编码(python3特性)
tcpCliSock.close()
tcpSerSock.close()
客户端的client.py如下所示:
#coding=utf-8
from socket import *
HOST = '10.0.64.60' #服务器的ip,和上面的server.py对应
PORT = 9090 #相同的端口
BUFSIZ = 1024
ADDR=(HOST,PORT)
tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
stock_codes = input('the stock_codes is > ') #客户输入想输入的stock_codes
if not stock_codes:
break
tcpCliSock.send(stock_codes.encode()) #向服务器端发送编码后的数据
stock_codes = tcpCliSock.recv(BUFSIZ).decode() #收到服务器端传过来的数据,解码
if not stock_codes:
break
print(stock_codes)
after_close_simulation = input('the after_close_simulation is > ')
if not after_close_simulation:
break
tcpCliSock.send(after_close_simulation.encode()) #发送编码后的数据
after_close_simulation = tcpCliSock.recv(BUFSIZ).decode() #收到数据,解码
if not after_close_simulation:
break
print(stock_codes)
tcpCliSock.close()
然后先运行服务器端的server.py,开始监听,然后再运行client.py,进行数据的传输就可以了。