Python server development 3: Socket

Source: Internet
Author: User

Socket is a continuation of I/O in the operating system. It can make communication between processes and machines possible. Socket can be regarded as a standard file descriptor. The difference is that the file needs to be opened using the open () function, while the socket uses socket ()

Function creation. recv (), send (), and read (), write () functions are very similar.

TCP generally uses accept () to create a new scoket for each connected client. Generally, UDP only uses a single socket and relies entirely on the value returned by recvfrom () to determine where to send a response.

 

Client:

1. Create a socket:

// AF_INET indicates IPv4
= socket.socket(socket.AF_INET, socket.SOCK_STREAM)

2. Connect to the socket

The socket connection requires a tuple parameter to provide the IP address and port number:

s.connect((“www.example.com”, 80))

3,

 =  = socket.getservbyname(,    %   , s.getpeername()

 

File objects:

= 70= sys.argv[1= sys.argv[2== s.makefile(+  line 

Advanced Interface:

= urllib.urlopen(sys.argv[1 1= f.read(2048 

 

 

Server:

1. Create a connection:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

2. Set socket options:

//1)

3. Bind a socket:

s.bind((host, port))

4. Listener:

s.listen(1)

5. Accept connections:

 1= 

6,

= Port = 51423 = 1 # It is set that there is only one request waiting for processing at a time. The real server will set a high number. S. listen (1 1 =

Use UDP:

=                                port = 51423=1 1= s.recvfrom(8192     

 

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.