首页 > 代码库 > 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