直接能用的python Socket多连接

 

1 环境:

python3 + Win10
功能1、采用子线程和处理每个TCP客户端连接
功能2、客户端连接和断开都有提示
功能3、数据回传

2 服务器源码:


# coding=utf-8
# !/usr/bin/env python
 
 
from socket import *
from time import ctime
import threading
import time
 
HOST = '192.168.10.51'
PORT = 1234
BUFSIZ = 1024
ADDR = (HOST, PORT)
 
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
socks = []  # 放每个客户端的socket

print('tcp server started. IP is %s, port: %d' % (HOST, PORT)) 
 
def clientthread_handle():
    while True:
        for s in socks:
            try:
                data = s.recv(BUFSIZ)  # 到这里程序继续向下执行
                if len(data)==0:
                    print("另一端断开了连接")
                    s.close()
                    socks.remove(s)
                    continue
                else:
                    str2send = ('[%s],%s' % (ctime(), data))
                    s.send(str2send.encode())
            except Exception as e:
                continue
 
t = threading.Thread(target=clientthread_handle)  # 子线程
if __name__ == '__main__':
    t.start()
    print( 'waiting for connecting...')
    while True:
        clientSock, addr = tcpSerSock.accept()
        print(  'connected from:', addr)
        clientSock.setblocking(0)
        socks.append(clientSock)
 

 使用时候只要修改运行主机的IP地址和端口。

3 客户端测试程序:

TCP/UDP 网络调试助手(PC版),http://wiki.ai-thinker.com/_media/tools/tcpudpdbg.zip

4 效果:

注意:使用的时候发现,若客户端使用一个固定的端口,在断开连接后的30秒时间内不能重连,在这个时间过后再按连接即可。


5 参考:


[1] Python socket 怎么判断连接断开,https://blog.csdn.net/qq_36145663/article/details/100543168?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

[2] Python Socket 网络编程,https://www.cnblogs.com/hazir/p/python_socket_programming.html

[3] python多线程模块:threading使用方法(参数传递),https://blog.csdn.net/chpllp/article/details/54381141

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值