Python Socket Communication Example

Source: Internet
Author: User
Tags socket connect

Innovation begins with imitation! The built-in socket module in python simplifies network programming. Next we will use two small scripts to understand how the client establishes a socket with the server. Client code: # clietn. pyif _ name _ = '_ main _': # determine whether to call itself, if not, _ name _ is the script name import socket # import the required socket module sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # The first step is to create a socket object. Call the socket constructor socket = socket. socket (family, type) family parameter to represent the address family, which can be AF_INET or AF_UNIX. The AF_INET family includes Internet addresses, and the AF_UNIX family is used for communication between processes on the same machine. The type parameter represents the socket type, which can be SOCK_STREAM (stream socket) and SOCK_DGRAM (datagram socket) sock. connect ('localhost', 7556) # Use the socket connect method to connect to the server. You must specify the Server ip address and port import time. sleep (2) sock. send ('1') # In the processing phase, the customer and server will communicate with the recv method through the send method. recv (1024) sock. close () # When the transmission ends, the customer calls the close method of socket to close the connection. Server code: # server. pyif _ name _ = '_ main _': import socket sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM) sock. bind ('localhost', 7556) # bind the socket to the specified address and port sock. listen (5) # Use the listen method of socket to receive connection requests. The parameters in brackets specify that up to five clients can be connected to the server. The value must be at least 1. After receiving the connection request, these requests need to be queued. If the queue is full, the request is rejected. While True: connection, address = sock. accept () # The server socket waits for the client to request a connection through the socket accept method. When the accept method is called, the socket enters the "waiting" status. When a customer requests a connection, the method establishes a connection and returns it to the server. The accept method returns a triple (connection, address) containing two elements ). The first element connection is the new socket object, and the server must communicate with the customer through it; the second element address is the customer's Internet address. Try: connection. settimeout (5) # Set the timeout buf = connection. recv (1024) # The server and client communicate (transmit data) through the recv method ). When calling recv, the server must specify an integer, which corresponds to the maximum data volume that can be received through this method call. The recv method enters the "blocked" status when receiving data, and returns a string that indicates the received data. If the amount of data sent exceeds the recv limit, the data will be truncated. The excess data is buffered at the receiving end. When recv is called in the future, excess data will be deleted from the buffer zone (and any other data that the customer may send since the last recv call ). If buf = '1': connection. send ('Welcome to python server! ') # The server calls send and uses a string to send messages to the client. The send method returns the number of sent characters. Else: connection. send ('please go out! ') Failed t socket. timeout: print 'time out' connection. close () # The transmission is over. The server calls the close method of socket to close the connection. Appendix: complete code #! /Usr/bin/env python # clietn. pyif _ name _ = '_ main _': import socket sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM) sock. connect ('localhost', 7556) import time. sleep (2) sock. send ('1') print sock. recv (1024) sock. close ()#! /Usr/bin/env python # server. pyif _ name _ = '_ main _': import socket sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM) sock. bind ('localhost', 7556) sock. listen (5) while True: connection, address = sock. accept () try: connection. settimeout (5) buf = connection. recv (1024) if buf = '1': connection. send ('Welcome to python server! ') Else: connection. send ('please go out! ') Wait t socket. timeout: print 'time out' connection. close ()

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.