Python socket client and service side handshake detailed description

Source: Internet
Author: User
This article mainly for you in detail the Python socket client and service side handshake, with a certain reference value, interested in small partners can refer to

Simple learning to use the socket to establish a connection between the client and the server and send the data

1. Client socketclient.py Code


Import socket  s = socket.socket (socket.af_inet, socket. SOCK_STREAM) # Establish connection: S.connect ((' 127.0.0.1 ', 9999)) # Receive Welcome message: print (S.RECV (1024x768). Decode (' Utf-8 ')) for data in [B ' Michael ' , B ' Tracy ', B ' Sarah ':  # Send data:  s.send (data)  print (S.RECV (1024x768). Decode (' Utf-8 ')) S.send (b ' exit ') s.close ()

2. Service-side serversocket.py code


Import Socket Import threading import time # from threading import Thread   s = socket.socket (socket.af_inet, socket. SOCK_STREAM) # Listening Port: 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 (b ' welcome! ')  While True:   data = SOCK.RECV (1024x768)   time.sleep (1)   if not data or Data.decode (' utf-8 ') = = ' exit ':    break< C9/>sock.send (' Hello,%s! '% data.decode (' Utf-8 ')). Encode (' Utf-8 '))  sock.close ()  print (' Connection from %s:%s closed. '% addr) while  True:  # accepts a new connection:  sock, addr = S.accept ()  # Create a new thread to handle the TCP connection:  t = Threa Ding. Thread (Target=tcplink, args= (sock, addr))  T.start ()

3. Operation Process

Open two console windows, run server Python3 serversocket.py first

Then run the client Python3 socketclient.py

The socket connection is as follows

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.