首页 > 代码库 > Python_socket_TCP
Python_socket_TCP
zServer.py
1 # coding=utf-8 2 import socket 3 words={‘how are you?‘:‘Fine,thank you.‘, 4 ‘how old are you?‘:‘25‘, 5 ‘what is your name?‘:‘zWrite‘, 6 ‘where do you word?‘:‘PopularWorker‘, 7 ‘bye‘:‘Bye‘} 8 HOST = ‘‘ 9 PORT = 50007 10 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 11 #绑定socket 12 s.bind((HOST,PORT)) 13 #开始监听 14 s.listen(1) 15 print(‘Listening at port:‘,PORT) 16 conn,address = s.accept() 17 print(‘Connected by‘,address) 18 while True: 19 data = http://www.mamicode.com/conn.recv(1024) 20 data =http://www.mamicode.com/ data.decode() 21 if not data: 22 break 23 print(‘Received message:‘,data) 24 conn.sendall(words.get(data,‘Nothing‘).encode()) 25 conn.close()
zClient.py
1 # coding=utf-8 2 import socket 3 4 HOST = ‘192.168.4.102‘ #服务器主机IP地址 5 PORT = 50007 #服务端主机端口号 6 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 7 s.connect((HOST,PORT)) #建立连接 8 while True: 9 c =input(‘Input the content you want to send:‘) 10 s.sendall(c.encode()) #发送数据 11 data = http://www.mamicode.com/s.recv(1024) #从客户端接受数据 12 data =http://www.mamicode.com/ data.decode() 13 print(‘Received:‘,data) 14 if c.lower() == ‘bye‘: 15 break 16 s.close() #关闭连接
先运行zServer.py再运行zClinet.py
Python_socket_TCP
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。