Multi-socket connection

 Multi-socket connection

This document is a document https://www.cnblogs.com/wodeboke-y/p/11241472.html

Subsequent content.

 

Case 2 on a document gives an obstructive type socket server

The following is a non-blocking, the following key points:

accept obstruction, using thread to solve

blocking socket, use setblocking solve

 

# 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)  # Here program execution continues down
           
the except Exception AS E:
                Continue
            IF Not
Data:
                socks.remove (S)
                Continue
           
s.send ( '[% S], S%' % (the ctime (), Data))


T = Threading .thread (= target handle)  # child threads
IF the __name__ == '__main__' :
    t.start ()
    print ( U ' I thread% s' .% threading.current_thread () name)  # itself is the main thread
   
print ( 'Waiting for Connecting ...' )
    the while True :
        clientSock, addr = tcpSerSock.accept ()
        Print ('connected from:', addr)
        clientSock.setblocking(0)
        socks.append(clientSock)

 

Guess you like

Origin www.cnblogs.com/wodeboke-y/p/11241555.html