Python TCP 协议网络编程《四》
点击上方蓝字,关注:无量测试之道
作者 | 无量测试之道
编辑 | 小 晴
这是无量测试之道的第151篇原创
server.py文件内容如下
1from socket import socket,SOCK_STREAM,AF_INET #导入模块
2from threading import Thread #导入线程包
3
4sockets=[] #用于存放所有请求过来的client的socket
5
6def tcp_server():
7 tcp_server_socket=socket(AF_INET,SOCK_STREAM) #创建TCP服务端套接字对接,UDP是SOCK_DGRAM
8 server_address=('127.0.0.1',9999)#定义本TCP服务端的ip and port
9 tcp_server_socket.bind(server_address) #绑定本机的8888端口
10 tcp_server_socket.listen(128) #设置监听,并设置最大等待连接数为128
11
12 while 1:
13 print("i'm accepting")
14 client_socket, client_info = tcp_server_socket.accept() # 接收客户端的socker and info
15 print(client_socket,client_info)
16 sockets.append(client_socket)
17 t=Thread(target=get_msg,args=(client_socket,)) #开启线程来处理当前请求过来的client
18 t.start()
19
20def get_msg(client_socket):
21 while 1:
22 data=client_socket.recv(1024)
23 print("the data:",data)
24 if(len(data)>0):
25 for sk in sockets:
26 print(sk,data)
27 sk.send(data)
28
29
30if __name__ == '__main__':
31 print("the TCP server is running ...")
32 tcp_server()
1from socket import socket,SOCK_STREAM,AF_INET #导入模块
2from threading import Thread #导入线程包
3import time
4
5tcp_client_socket = socket(AF_INET, SOCK_STREAM) # 创建TCP客户端套接字对接
6server_address = ('127.0.0.1', 9999) # 定义本TCP服务端的ip and port
7tcp_client_socket.connect(server_address) # 连接到服务端
8
9def tcp_client():
10 thread1=Thread(target=read_msg,args=(tcp_client_socket,))
11 thread1.start()
12
13 thread2= Thread(target=send_msg, args=(tcp_client_socket,))
14 thread2.start()
15
16def send_msg(tcp_client_socket):
17 while 1:
18 message=input(">>>")
19 tcp_client_socket.send(message.encode("utf-8"))
20 time.sleep(1)#这里稍微等一下发送的消息返回,否则会看到输入>>>标识的错位
21
22def read_msg(tcp_client_socket):
23 while 1:
24 resv_data = tcp_client_socket.recv(1024)
25 print("the get of message is:",resv_data.decode("utf-8"))
26
27if __name__ == '__main__':
28 print("the TCP client is running ...")
29 tcp_client()
1the TCP client is running ...
2>>>good good study
3the get of message is: good good study
4>>>day day up
5the get of message is: day day up
6>>>
你的鼓励将会是我创作的最大动力。
点个赞,点个在看再走吧~~~