Python Basic-socket Communication

Source: Internet
Author: User

The socket is a starting point and a focus for two-way communication, the ambience server side and the client

The socket server side uses the method to have

Method Description
S.bind () This method binds the address (hostname, port number pair) to the socket.
S.listen () This method sets the up and start TCP listener.
S.accept () This passively accept TCP client connection, waiting until connection arrives (blocking).

The method used by the socket client is

Method Description
S.connect () This method actively initiates TCP server connection.

The socket general method has

Method Description
S.RECV () This method receives TCP message
S.send () This method transmits TCP message
S.recvfrom () This method receives UDP message
S.sendto () This method transmits UDP message
S.close () This method closes socket
Socket.gethostname () Returns the hostname.

The following is an example of a simple socket communication, including a socket server to listen to a local server port, a socket client sends a request to the server side. A message is returned after a request is received by the server side

Socket Server Side

Created a simple socket that binds to the port on the local server to provide services externally. The supervisor responds when he hears the request.

S.listen indicates start monitoring, number of listening queue is 5

1 ImportSocket2 3 #Create a socket Object,and bind it to the port4s=Socket.socket ()5Host =Socket.gethostname ()6Port = 123457 S.bind ((host,port))8 9S.listen (5)Ten  One  whileTrue: AC,ADDR =s.accept () -     Print 'Got connectoion from', addr -C.send ('thank from connecting') theC.close ()

Socket Client

Import sockets== = 12345s.connect ((host,port))print s.recv (1024x768) s.close ()

Python Basic-socket Communication

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.