Python's TCP socket programming details and simplicity

Source: Internet
Author: User
Python TCP Socket programming detailed

Beginner script Language Python, test the available TCP communication programs:

Server:

#!/usr/bin/env python #-*-coding:utf-8-*-  Import Socket import Threading import Time  def tcplink (sock, addr): C4/>print (' Accept new connection from%s:%s ... '% addr);   Sock.send (b ' Welcome!!! ');   While True:     data = SOCK.RECV (1024x768);     Time.sleep (1);     If not data or Data.decode (' utf-8 ') = = ' exit ': Break        ;     Sock.send (b ' Hello,%s! '% data);   Sock.close ();   Print (' Connection from%s:%s closed. '% addr);   if __name__ = = "__main__":    s = socket.socket (socket.af_inet, socket. SOCK_STREAM);    S.bind ((' 127.0.0.1 ', 9090));   S.listen (8); #监听8个客户端;   print (' Waiting for connection ... ');    While True:     sock, addr = S.accept ();     t = Threading. Thread (Target=tcplink, args= (SOCK,ADDR));     T.start ();

Client:

#!/usr/bin/env python #-*-coding:utf-8-*-  import socket  s = socket.socket (socket.af_inet, socket. SOCK_STREAM); S.connect ((' 127.0.0.1 ', 9090)); Print (S.RECV (1024x768). Decode (' Utf-8 ')); For data in [b ' lk ', b ' AA ', b ' BB ']:   s.send (data);   Print (S.RECV (1024x768). Decode (' Utf-8 ')); S.send (b ' exit '); S.close ();

Thank you for reading, hope to help everyone, thank you for the support of this site!

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.