码迷,mamicode.com
首页 > 编程语言 > 详细

Python_socket_TCP

时间:2017-06-23 23:46:30      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:连接   add   address   listen   .com   com   data   soc   while   

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 = conn.recv(1024)
20     data = 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 = s.recv(1024) #从客户端接受数据
12     data = data.decode()
13     print(Received:,data)
14     if c.lower() == bye:
15         break
16 s.close()   #关闭连接

先运行zServer.py再运行zClinet.py

技术分享

技术分享

 

Python_socket_TCP

标签:连接   add   address   listen   .com   com   data   soc   while   

原文地址:http://www.cnblogs.com/cmnz/p/7071912.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!