python中的socket+threading多執行緒

One of them發表於2018-08-23

socket的threading多執行緒使用

# 多執行緒.
import threading
import socket


def func(cnn):
    while True:
        try:
            request = cnn.recv(1024)
            print(request)
            cnn.send(b'%s' % request)
        # cnn.close()
        except ConnectionResetError:
            pass


if __name__ == "__main__":
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('0.0.0.0', 4444))
    s.listen(5)

    while True:
        cnn, addr = s.accept()
        th = threading.Thread(target=func, args=(cnn,), daemon=True)
        th.start()

相關文章