socket 多连接

 socket 多连接

本文档为文档https://www.cnblogs.com/wodeboke-y/p/11241472.html

后续内容。

上一文档中的案例2给出了一个阻塞型socket server

下面为非阻塞型,关键点如下:

accept阻塞,使用thread解决

socket阻塞,使用setblocking解决

# coding=utf-8
# !/usr/bin/env python
'''

'''

from socket import *
from time import ctime
import threading
import time

HOST = ''
PORT = 2159
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
socks = []  # 放每个客户端的socket


def handle():
    while True:
        for s in socks:
            try:
                data = s.recv(BUFSIZ)  # 到这里程序继续向下执行
           
except Exception as e:
                continue
            if not
data:
                socks.remove(s)
                continue
           
s.send('[%s],%s' % (ctime(), data))


t = threading.Thread(target=handle)  # 子线程
if __name__ == '__main__':
    t.start()
    print(u'我在%s线程中 ' % threading.current_thread().name)  # 本身是主线程
   
print('waiting for connecting...')
    while True:
        clientSock, addr = tcpSerSock.accept()
        print('connected from:', addr)
        clientSock.setblocking(0)
        socks.append(clientSock)

猜你喜欢

转载自www.cnblogs.com/wodeboke-y/p/11241555.html