Multi-threaded Network connections

Source: Internet
Author: User

The client uses multithreading to accept requests from multiple users and never exits.

Server-side
#!/usr/bin/env python#-*- coding:utf-8 -*-import socketimport threading, times = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind((‘127.0.0.1‘, 9999))s.listen(5)print ‘Waiting for connection...‘def tcplink(sock, addr):    print ‘Accept new connection from %s:%s...‘ % addr    sock.send(‘Welcome!‘)    while True:        data = sock.recv(1023)        time.sleep(1)        if data == ‘exit‘ or not data:            break        sock.send(‘Hello, %s!‘ %data)    sock.close()    print ‘Connection from %s:%s closed.‘ % addrwhile True:    sock, addr = s.accept()    #创建新进程来出来新的TCP连接    t = threading.Thread(target=tcplink, args=(sock, addr))    t.start()
Client
#!/usr/bin/env pythonimport sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((‘127.0.0.1‘, 9999))print s.recv(1024)for data in [‘Michael‘, ‘Tracy‘, ‘Sarah‘]:    s.send(data)    print s.recv(1024)s.send(‘exit‘)s.close()

Multi-threaded Network connections

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.