今日主题:使用Python 实现Server和Client的互相交流沟通
今天分享的内容是在上一篇文章Python TCP 协议网络编程《一》的基础上进行的一次改造,使Server和Client可以互相交流沟通,server.py与client.py文件内容是具体的实现代码。
server.py文件内容:
1from socket import socket,SOCK_STREAM,AF_INET #导入模块 2def tcp_server(): 3 tcp_server_socket=socket(AF_INET,SOCK_STREAM) #创建TCP服务端套接字对接,UDP是SOCK_DGRAM 4 server_address=('127.0.0.1',8888)#定义本TCP服务端的ip and port 5 tcp_server_socket.bind(server_address) #绑定本机的8888端口 6 tcp_server_socket.listen() #执行监听 7 client_socket,client_info = tcp_server_socket.accept() #接收客户端的socker and info 8 while 1: 9 data=client_socket.recv(1024)#接收客户端发过来的消息 10 print("the client say:",data)#打印客户端发送过来的信息 11 server_answer=input('>>>')#从键盘录入信息 12 client_socket.send(server_answer.encode("utf-8")) 13 14if __name__ == '__main__': 15 print("the TCP server is running ...") 16 tcp_server()
步骤如下:
-
导入模块
-
建立TCP socket连接
-
绑定ip 和 port
-
启动监听
-
等待accept
-
一直循环接收客户端的请求
-
打印客户端的消息
-
输入消息并回复给客户端
client.py文件内容:
1from socket import socket,SOCK_STREAM,AF_INET #导入模块 2def tcp_client(): 3 tcp_client_socket=socket(AF_INET,SOCK_STREAM) #创建TCP客户端套接字对接 4 server_address=('127.0.0.1',8888)#定义本TCP服务端的ip and port 5 tcp_client_socket.connect(server_address) #连接到服务端 6 while 1: 7 message=input("client>>>") #定义要发送的消息 8 tcp_client_socket.send(message.encode("utf-8"))#向服务端发送消息 9 response=tcp_client_socket.recv(1024) 10 print("the server say:",response.decode("utf-8")) 11 12if __name__ == '__main__': 13 print("the TCP client is running ...") 14 tcp_client() 15 print("the message was send")
步骤如下:
-
导入模块
-
建立TCP socket连接
-
连接到服务端监听的ip 和 port
-
一直循环输入消息并发送给服务端
-
接收服务端返回的消息
-
打印服务端返回的消息
Server and Client 对应的输出:
1client console output: 2the TCP client is running ... 3client>>>hello tony 4the server say: hello jack 5client>>>how are you 6the server say: i'm fine 7client>>> 8
Server Console 对应的输出:
1the TCP server is running ... 2the client say: b'hello tony' 3>>>hello jack 4the client say: b'how are you' 5>>>i'm fine