Python socket处理client连接过程解析
作者:flag_HW 时间:2022-04-30 15:44:31
socket只能处理一个client连接,如果需要并发处理多个链接则需要使用socketserver,下面是代码示例以及注释
server端
import socketserver
#之前的socket只能同时处理一个客户端,当需要并发处理client发送的信息是需要使用到socketserver,下面创建一个类,继承socketserver其对应实例就有并发能力
class My_Tcp_Handler(socketserver.BaseRequestHandler):
#下面的handler是自己定义的server与client交互的过程,所有交互过程都在此方法内部实现.方法名handle是固定的
def handle(self):
while True:
try:
#下面将收到的数据打印并且大写后发回给客户端
self.data = self.request.recv(1024)
print(self.data.decode(encoding="utf-8"))
self.send_data = self.data.decode(encoding="utf-8").upper().encode(encoding="utf-8")
self.request.sendall(self.send_data)
except ConnectionResetError as e:
print("一个客户端关闭了连接")
break
#实例化socketserver
My_server = socketserver.ThreadingTCPServer(("0.0.0.0", 8888), My_Tcp_Handler) #ThreadingTCPServer是使用多线程,ForkingTCPServer是使用多进程处理并发
#启动实例
My_server.serve_forever()
下面是client端
import socket
client = socket.socket()
client.connect(("127.0.0.1", 8888))
while True:
msg = input()
if len(msg) == 0:
continue
client.send(msg.encode(encoding="utf-8")) #如果发送中文需要对其进行encode,接收也需要decode;英文前面直接加b指定类型
client_rec = client.recv(1024).decode(encoding="utf-8")
print("client_rec:", client_rec)
client.close()
来源:https://www.cnblogs.com/flags-blog/p/12369399.html
标签:Python,socket,client
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python脚本打包后无法运行exe文件的解决方案
2021-02-25 23:25:35
![](https://img.aspxhome.com/file/2023/7/70147_0s.jpg)
python中numpy包使用教程之数组和相关操作详解
2022-10-26 19:18:40
Python异常信息的不同展现方法总结
2021-02-20 10:14:26
![](https://img.aspxhome.com/file/2023/7/90547_0s.png)
深入浅析python定时杀进程
2021-10-23 17:14:15
页面重构应注意的repaint和reflow
2011-03-31 17:11:00
在python中bool函数的取值方法
2021-10-06 00:47:37
PPOCRLabel标注的txt格式如何转换成labelme能修改的json格式
2021-08-31 06:01:45
![](https://img.aspxhome.com/file/2023/7/107087_0s.jpg)
如何基于Python爬取隐秘的角落评论
2022-02-17 05:31:43
![](https://img.aspxhome.com/file/2023/2/87902_0s.jpg)
pytorch_detach 切断网络反传方式
2022-09-25 21:10:50
JS打开新窗口的2种方式
2023-07-07 02:44:49
PDO::query讲解
2023-06-08 18:09:37
Python 26进制计算实现方法
2022-12-09 03:26:36
python爬虫抓取时常见的小问题总结
2023-03-18 07:34:07
![](https://img.aspxhome.com/file/2023/1/109661_0s.webp)
python3 numpy中数组相乘np.dot(a,b)运算的规则说明
2022-05-08 16:23:29
![](https://img.aspxhome.com/file/2023/5/99145_0s.jpg)
Python爬虫beautifulsoup4常用的解析方法总结
2022-09-01 11:58:54
python3.7 打包成exe程序方式(只需两行命令)
2023-01-26 14:29:34
![](https://img.aspxhome.com/file/2023/3/114603_0s.png)
python新手学习使用库
2021-06-20 13:08:38
基于python实现从尾到头打印链表
2023-07-02 21:24:34
Python编程之列表操作实例详解【创建、使用、更新、删除】
2021-12-24 19:03:03
![](https://img.aspxhome.com/file/2023/9/107579_0s.jpg)
Django实现内容缓存实例方法
2021-04-19 20:47:41