TCP编程
服务器端代码
''' connect(address) 链接远程计算机 send(bytes[,flags]) 发送数据 recv(bufsize[,flags]) 发送数据 bind(address) 绑定地址 listen() 开始接听,等待客户端连接 accept() 响应客户请求 sendall() 发送全部信息 ''' ''' 服务端代码 ''' import socket words = {'how are you?':'Fine,thank you', 'how old are you':'18', 'what you name?':'LuoJiaHong', 'what is you name':'LuoJIaHong', 'where do you work':'SDIBT', 'bye':'Bye' } HOST = '' PORT = 50007 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #绑定socket,服务器的ip随意,端口号是50007 s.bind((HOST,PORT)) #开始监听,变为服务器,参数表示可同时服务的客户端数量 s.listen(1) print('Listening at port:',PORT) #conn,是用于数据发送的套接字,就像是一把独属服务器的锁 conn,addr = s.accept() print('Connected by',addr) while True: #每次能够传输1024字节,同时转换字符 data = conn.recv(1024).decode() #接收到空串,没有收到的数据,表示对方已经关闭 if not data: break print('Received message:',data) conn.sendall(words.get(data,'Nothing').encode()) conn.close() s.close()
客户端代码
import sys import socket HOST = '172.26.48.1' PORT = 50007 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((HOST,PORT)) except Exception as e: print('Server not found or not open') sys.exit() while True: c = input('Input the content you want to send:') s.sendall(c.encode()) #从服务器端接收数据字节串,然后解码为字符串 data = s.recv(1024).decode() print('Received:',data) if c.lower() == 'bye': break s.close()标签:网络通信,socket,Python,TCP,HOST,print,data,PORT,conn From: https://www.cnblogs.com/buchijiuminvhai/p/17065449.html