直接能用的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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章