1 Environment:
python3 + Win10
function 1. Use sub-threads and handle each TCP client connection
function 2. Client connection and disconnection have prompt
function 3. Data return
2 Server source code:
# 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)
When using, just modify the IP address and port of the running host.
3 Client test program:
TCP/UDP network debugging assistant (PC version), http://wiki.ai-thinker.com/_media/tools/tcpudpdbg.zip
4 Effect:
Note: When using it, it is found that if the client uses a fixed port, it cannot reconnect within 30 seconds after disconnection. After this time, press connect again.
5 Reference:
[1] How does Python socket determine that the connection is disconnected, 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 network programming, https://www.cnblogs.com/hazir/p/python_socket_programming.html
[3] Python multithreading module: How to use threading (parameter transfer), https://blog.csdn.net/chpllp/article/details/54381141