Introduction to basic socket programming in Python, pythonsocket

Source: Internet
Author: User

Introduction to basic socket programming in Python, pythonsocket

In network communication, sockets are almost everywhere. It can be seen as an intermediate software abstraction layer for communications between the application layer and the TCP/IP protocol cluster. It is an interface for two applications to communicate with each other, in addition, the complex TCP/IP protocol details are hidden behind the interface. Python provides the socket module for convenient socket programming.

Create a server socket
Use the socket method to create a new socket. Generally, two parameters are provided. The first parameter is address family, and the second parameter is socket type.

#create an INET, STREAMing sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

The preceding Code creates a socket with the address family as the IP protocol and the Transport Protocol as the TCP protocol.

After creating a socket, the server needs to bind it to an IP address and port to provide services. This requires the bind method.

# bind the socket to all available interfaces on port 8888s.bind(('', 8888))

Use the listen method to set the socket to the listening status. The listen method is followed by a parameter, indicating the maximum number of requests that can be received in the queue.

#become a server socketserversocket.listen(5)

Now, we have created a server socket, and then compiled an infinite loop body to receive connections from the client. Using the accept method, it returns a new socket, indicating a connection to the remote end, at the same time, an address pair is returned, indicating the IP address and port number of the remote connection.

# enter the main loop of the web serverwhile 1:  #accept connections from outside, return a pair (conn, addr)  (clientsocket, address) = serversocket.accept()  #now do something with the clientsocket  #in this case, we'll pretend this is a threaded server  ct = client_thread(clientsocket)  ct.run()

Generally, the server socket in the loop body does not send or receive any data, but only receives remote connections and sends new connections to other threads for processing, then, listen for more other connections. Otherwise, when processing a connection, it will not be able to accept other new connections.

Next, we create a thread to process the connection. First, use the recv method to accept data from the socket, followed by a parameter to indicate the maximum acceptable data size at a time. Then, use the sendall method to reply to the socket. sendall continuously sends data until all data is sent completely or an exception occurs. Finally, remember to close the socket because each socket represents a file descriptor in the system. If it is not closed in time, it may exceed the maximum number of file descriptors in the system, A new socket cannot be created.

def handle_request(sock, addr):  print "Accept new connection from {addr}".format(addr = addr)  request_data = client_connection.recv(1024)  print request_data.decode()  http_response = "Hello, world!"  # send response data to the socket  sock.sendall(http_response)  sock.close()

Summary server socket mainly consists of the following steps:

  • Create a new server socket;
  • Bind the socket to an address and port;
  • Listen for remote connections;
  • Accept connections and distribute them to other threads for processing.

The following is the complete server socket sample code:

import socketimport threadingSERVER_ADDRESS = (HOST, PORT) = '', 8888REQUEST_QUEUE_SIZE = 1024def handle_request(sock, addr):  print "Accept new connection from {addr}".format(addr = addr)  request_data = client_connection.recv(1024)  print request_data.decode()  http_response = "Hello, world!"  # send response data to the socket  sock.sendall(http_response)  sock.close()def serve_forever():  server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # reuse socket immediately  server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  server_socket.bind(SERVER_ADDRESS)  server_socket.listen(REQUEST_QUEUE_SIZE)  print 'Serving HTTP on port {port} ...'.format(port = PORT)  while True:    try:      client_connection, client_address = server_socket.accept()    except IOError as e:      code, msg = e.args      # restart 'accept' if it was interrupted      if code == errno.EINTR:        continue      else:        raise    # create a thread to handle this request    t = threading.Thread(target=handle_request, args=(sock, addr))    t.start()if __name__ == '__main__':  serve_forever()

Create a client socket
The client socket is relatively simple, mainly including the following steps:

  • Create a socket;
  • Connect to the server;
  • Send data to the server;
  • Receives data from the server;
  • Disable socket.
import socketHOST = 'localhost' # the remote hostPORT = 8888 # port used by serverclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# connect to serverclient_socket.connect((HOST, PORT))# send something to the serverclient_socket.sendall("Hello, world")data = client_socket.recv(1024)client_socket.close()print 'Received', repr(data)

PS: socket module usage Extension

sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)

Parameter 1: address cluster

Socket. AF_INET IPv4 (default)
Socket. AF_INET6 IPv6

Socket. AF_UNIX can only be used for inter-process communication in a single Unix System

Parameter 2: Type

Socket. SOCK_STREAM streaming socket, for TCP (default)
Socket. SOCK_DGRAM datagram socket, for UDP

Socket. the original socket of SOCK_RAW. A common socket cannot process network packets such as ICMP and IGMP, while SOCK_RAW can. Secondly, SOCK_RAW can also process special IPv4 packets. In addition, the original socket, you can use the IP_HDRINCL socket option to construct an IP address header.
Socket. SOCK_RDM is a reliable UDP format, that is, ensure the delivery of datagram but not the order. SOCK_RAM is used to provide low-level access to the original protocol. It is used when special operations are required, such as sending ICMP packets. SOCK_RAM is generally only used by programs run by senior users or administrators.
Socket. SOCK_SEQPACKET reliable continuous packet Service

Parameter 3: Protocol

0 (default) is a protocol related to a specific address family. If it is 0, the system automatically selects a suitable protocol based on the address format and set type.

Sk. bind (address)

S. bind (address) binds the socket to the address. The address format depends on the address family. In AF_INET, the address is expressed in the form of a tuple (host, port.

Sk. listen (backlog)

Start listening for incoming connections. Backlog specifies the maximum number of connections that can be suspended before a connection is rejected.

Backlog = 5 indicates that the kernel has received a connection request, but the server has not called accept to process up to 5 connections.
This value cannot be infinitely large because the connection queue needs to be maintained in the kernel.

Sk. setblocking (bool)

Whether to block (True by default). If False is set, an error is returned if no data exists in accept and recv.

Sk. accept ()

Accept the connection and return (conn, address). conn is a new socket object and can be used to receive and send data. Address is the address used to connect to the client.

Receive TCP client connection (blocking) waiting for connection arrival

Sk. connect (address)

Connect to the socket at address. Generally, the format of address is tuples (hostname, port). If a connection error occurs, the socket. error is returned.

Sk. connect_ex (address)

The same as above, but there will be a return value. When the connection is successful, 0 is returned, and the encoding is returned when the connection fails, for example: 10061

Sk. close ()

Disable socket

Sk. recv (bufsize [, flag])

Accept socket data. The data is returned as a string. The bufsize specifies the maximum number of messages that can be received. Flag provides other information about messages, which can be ignored.

Sk. recvfrom (bufsize [. flag])

Similar to recv (), but the return value is (data, address ). Data is the string containing the received data, and address is the socket address for sending data.

Sk. send (string [, flag])

Send the data in the string to the connected socket. The returned value is the number of bytes to be sent, which may be smaller than the size of the string.

Sk. sendall (string [, flag])

Send data in string to the connected socket, but try to send all data before returning. If None is returned successfully, an exception is thrown.

Sk. sendto (string [, flag], address)

Sends data to the socket. The address is a tuples in the form of (ipaddr, port) and specifies the remote address. The returned value is the number of bytes sent. This function is mainly used for UDP.

Sk. settimeout (timeout)

Sets the superperiod of socket operations. timeout is a floating point number in seconds. If the value is None, there is no superperiod. Generally, it should be set when the socket is just created during off-peak periods, because they may be used for connection operations (for example, a client connection can wait up to 5 s)

Sk. getpeername ()
This method can only be used on the client to view information on the server.
Returns the remote address of the socket. The returned value is usually a tuples (ipaddr, port ).

Sk. getsockname ()
This method can only be used on the server and used to view the information of the server.
Return the address of the socket. It is usually a tuple (ipaddr, port)

Sk. fileno ()

Socket file descriptor

Related Article

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.