Python TCP 协议网络编程《三》
Posted 无量测试之道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python TCP 协议网络编程《三》相关的知识,希望对你有一定的参考价值。
点击上方蓝字,关注:无量测试之道
作者 | 无量测试之道
编辑 | 小 晴
这是无量测试之道的第150篇原创
1from socket import socket,SOCK_STREAM,AF_INET #导入模块
2
3def tcp_server():
4 tcp_server_socket=socket(AF_INET,SOCK_STREAM) #创建TCP服务端套接字对接,UDP是SOCK_DGRAM
5 server_address=('127.0.0.1',9999)#定义本TCP服务端的ip and port
6 tcp_server_socket.bind(server_address) #绑定本机的9999端口
7 tcp_server_socket.listen() #执行监听
8 client_socket,client_info = tcp_server_socket.accept() #接收客户端的socker and info
9 while 1:
10 data=client_socket.recv(1024)#接收客户端发过来的消息
11 datas=data.decode("utf-8")
12 if(len(datas)>1):
13 print("the client say:",datas)#打印客户端发送过来的信息
14 if(datas=="bye"):
15 break
16 server_answer=input('>>>')#从键盘录入信息
17 client_socket.send(server_answer.encode("utf-8"))
18
19if __name__ == '__main__':
20 print("the TCP server is running ...")
21 tcp_server()
1import time
2
3from socket import socket,SOCK_STREAM,AF_INET #导入模块
4
5
6def connection_socket():
7 tcp_client_socket = socket(AF_INET, SOCK_STREAM) # 创建TCP客户端套接字对接
8 server_address = ('127.0.0.1', 9999) # 定义本TCP服务端的ip and port
9 try:
10 tcp_client_socket.connect(server_address) # 连接到服务端
11 except:
12 print("connection failed!!!")
13 exit(0)
14 return tcp_client_socket
15
16def tcp_client():
17 while 1:
18 try:
19 tcp_client_socket=connection_socket()
20 message=input("client>>>") #定义要发送的消息
21 print("the message is:",message)
22 print(tcp_client_socket)
23 tcp_client_socket.send(message.encode("utf-8"))#向服务端发送消息
24 response=tcp_client_socket.recv(1024)
25 print("the server say:",response.decode("utf-8"))
26 except:
27 tcp_client_socket.close()#关闭原有socket连接
28 print("the socket connection is failed, try again to reconnection...")
29 time.sleep(3)
30
31if __name__ == '__main__':
32 print("the TCP client is running ...")
33 tcp_client()
34 print("the message was send")
1the TCP client is running ...
2
3client>>>abc
4the message is: abc
5<socket.socket fd=200, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 55699), raddr=('127.0.0.1', 9999)>
6the server say: def
7
8client>>>aa
9the message is: aa
10<socket.socket fd=1888, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 55700), raddr=('127.0.0.1', 9999)>
11the socket connection is failed, try again to reconnection...
12
13client>>>abc
14the message is: abc
15<socket.socket fd=1888, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 55703), raddr=('127.0.0.1', 9999)>
16the server say: def
17client>>>
18
你的鼓励将会是我创作的最大动力。
点个赞,点个在看再走吧~~~
以上是关于Python TCP 协议网络编程《三》的主要内容,如果未能解决你的问题,请参考以下文章