python3 + Win10
功能1、采用子线程和处理每个TCP客户端连接
功能2、客户端连接和断开都有提示
功能3、数据回传
# 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地址和端口。
TCP/UDP 网络调试助手(PC版),http://wiki.ai-thinker.com/_media/tools/tcpudpdbg.zip
注意:使用的时候发现,若客户端使用一个固定的端口,在断开连接后的30秒时间内不能重连,在这个时间过后再按连接即可。
[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