码迷,mamicode.com
首页 > 其他好文 > 详细

socket 多连接

时间:2019-07-25 00:40:04      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:locking   https   server   host   try   tcp   lis   使用   while   

 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)

 

socket 多连接

标签:locking   https   server   host   try   tcp   lis   使用   while   

原文地址:https://www.cnblogs.com/wodeboke-y/p/11241555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!