Detailed Python socket network programming

Source: Internet
Author: User
Socket is a way of inter-process communication, and it is a major difference between the communication with other processes: it can achieve inter-process communication between different hosts, the various services on our network are based on the Socket to complete the communication, such as our daily web browsing, QQ Chat, send and receive email and so on. To solve the process communication problem between two hosts on the network, first to uniquely identify the process, in the TCP/IP network protocol, is through (IP address, protocol, port number) ternary group to identify the process, solve the process identity problem, there is the basis of communication.

This article mainly introduces the use of Python for TCP Socket network programming, assuming you already have a preliminary network knowledge and Python basic grammar knowledge.

TCP is a connection-oriented transport layer protocol, the TCP Socket is based on a client-server programming model, the server listens to the client's connection request, once the connection is established can transfer data. Then the introduction of TCP Socket programming is also divided into the client and server:

One, client-side programming
Create socket

The first thing to do is to create a socket, which can be done using the function socket of the socket module in Python:

#Socket Client example in Python import socket  #for sockets #create a af_inet, STREAM socket (TCP) s = Socket.socket (s Ocket.af_inet, Socket. sock_stream) print ' Socket Created '

The function Socket.socket creates a socket that returns a descriptor for that socket, which will be used in subsequent related functions. The function has two parameters:

Address Family: You can choose Af_inet (for Internet interprocess communication) or Af_unix (for the same machine inter-process communication)
Type: Socket type, either socket_stream (stream socket, primarily for TCP protocol) or Socket_dgram (datagram socket, primarily for UDP protocol)
Note: As this article mainly outlines the Python Socket programming process, so the relevant function parameters, return values are not described in detail, you need to understand the relevant manuals can be viewed

Error handling

If creating the socket function fails, it throws an Socket.error exception that needs to be captured:

#handling errors in Python socket programs import socket  #for socketsimport sys #for exit try:  #create an af_inet, STREAM socket (TCP)  s = socket.socket (socket.af_inet, socket. SOCK_STREAM) except Socket.error, msg:  print ' Failed to create socket. Error code: ' + str (msg[0]) + ', Error message: ' + msg[1]  sys.exit (); print ' Socket Created '

So far the socket has been successfully created, and then we will use this socket to connect to a server, even www.google.com.

Connecting to a server

This article began by mentioning that the socket uses (IP address, protocol, port number) to identify a process, then we want to communicate with the server, we need to know its IP address and port number.

Obtain the IP address of the remote host

Python provides a simple function socket.gethostbyname to obtain the IP address of the remote host:

Host = ' www.google.com ' port = try:  remote_ip = socket.gethostbyname (host) except Socket.gaierror:  #could not Resolve  print ' Hostname could not being resolved. Exiting '  sys.exit ()   print ' Ip address of ' + host + ' is ' + remote_ip

Now that we know the IP address of the server, we can connect to a specific port on the IP using the connection function connect, and the following example connects to port 80 (the default port for the HTTP service):

#Connect to Remote Servers.connect ((REMOTE_IP, port)) print ' Sockets Connected to ' + Host + ' on IP ' + remote_ip

Run the program:

$ python client.pysocket createdip of remote host www.google.com is 173.194.38.145Socket Connected to www.google.com on IP 173.194.38.145

Send data

The above indicates that the connection to the www.google.com has been successful, then we can send some data to the server, for example, send string get/http/1.1\r\n\r\n, which is an HTTP request page Content command.

#Send some data to remote ServerMessage = "get/http/1.1\r\n\r\n" Try:  #Set the whole string  s.sendall (message) E Xcept socket.error:  #Send failed  print ' send failed '  sys.exit () print ' Message send successfully '

After the data is sent, the client also needs to accept the server's response.

Receive data

The function recv can be used to receive data from the socket:

#Now Receive datareply = S.RECV (4096) Print reply

The results of running together are as follows:

Socket Createdip of remote host www.google.com is 173.194.38.145Socket Connected to www.google.com on IP 173.194.38.145Mes Sage Send successfullyhttp/1.1 302 foundcache-control:privatecontent-type:text/html; Charset=utf-8location:http://www.google.com.sg/?gfe_rd=cr&ei=plqjvlcreovw8gff0og4cqcontent-length:262date: Thu, Dec 08:47:58 gmtserver:gfe/2.0alternate-protocol:80:quic,p=0.02
 
  302 Moved

302 Moved

The document has movedhere.

Close socket

When we do not want to request the server data again, we can close the socket and end this communication:

S.close ()
Summary

Above we learned how to:

    • Create socket
    • Connect to a remote server
    • Send data
    • Receive data
    • Close socket

When we open www.google.com, this is what the browser does, and it makes sense to know that. In a socket with this behavior characteristic is called client, the client is mainly connected to the remote system to obtain data.

Another behavior in the socket is called server, and the server uses the socket to receive connections and provide data, just the opposite of the client. So www.google.com is the server, your browser is the client, or more accurately, www.google.com is the HTTP server, your browser is the HTTP client.

Then the above describes the client programming, now the server side if the socket is used.

Second, server-side programming
The server side mainly does the following work:

    • Open socket
    • Bind to a specific address and on a port
    • Listening to connections
    • Establish a connection
    • Receive/Send data

The above describes how to create a socket, the next step is binding.

Bind socket

The function bind can be used to bind a socket to a specific address and port, which requires a sockaddr_in structure as an argument:

Import socketimport sys HOST = '  # symbolic name meaning all available interfacesport = 8888 # arbitrary non-privile Ged Port s = socket.socket (socket.af_inet, socket. sock_stream) print ' Socket created ' try:  s.bind ((HOST, PORT)) except Socket.error, msg:  print ' bind failed. Error Code: ' + str (msg[0]) + ' Message ' + msg[1]  sys.exit ()   print ' Socket bind complete '

After the binding is complete, the next step is to listen for the connection.

Listening to connections

The function listen can put the socket in listening mode:

S.listen (Ten) print ' Socket now listening '

The function has a parameter called a backlog, which controls the number of connections. If set to 10, then there are 10 connections waiting to be processed, at which point a 11th request will be rejected.

Receive connection

When a client sends a connection request to the server, the server receives the connection:

#wait to accept a connection-blocking callconn, addr = s.accept () #display client Informationprint ' Connected with ' + A Ddr[0] + ': ' + str (addr[1])

Running the program, the output is as follows:

$ python server.pysocket createdsocket bind completesocket now listening

At this point, the program waits for the request to arrive on port 8888. Do not turn off this program, let it run, now the client can connect to the socket via this port. We use Telnet client to test, open a terminal, enter telnet localhost 8888:

$ telnet localhost 8888Trying 127.0.0.1...Connected to localhost. Escape character is ' ^] '. Connection closed by foreign host.

At this point the server output will display:

$ python server.pysocket createdsocket bind completesocket now listeningconnected with 127.0.0.1:59954

We observed that the client is already connected to the server. After the connection is established, we can use it to communicate with the client. The following example shows that after the server establishes the connection, receives the data sent by the client and immediately sends the data back, the following is the complete service-side program:

Import socketimport sys HOST = '  # symbolic name meaning all available interfacesport = 8888 # arbitrary Non-privileg Ed Port s = socket.socket (socket.af_inet, socket. sock_stream) print ' Socket created ' try:  s.bind ((HOST, PORT)) except Socket.error, msg:  print ' bind failed. Error Code: ' + str (msg[0]) + ' Message ' + msg[1]  sys.exit ()   print ' Socket bind complete ' S.listen (Ten) print ' Soc  Ket now listening ' #wait to accept a connection-blocking callconn, addr = s.accept () print ' Connected with ' + addr[0] + ': ' + str (addr[1]) #now keep talking with the Clientdata = Conn.recv (1024x768) conn.sendall (data) Conn.close () S.close ()

Run this program in one terminal, open another terminal, use Telnet to connect to the server, enter the string randomly, and you will see:

$ telnet localhost 8888Trying 127.0.0.1...Connected to localhost. Escape character is ' ^] '. Happyhappyconnection closed by foreign host.

The client (Telnet) received a response from the server.

After we have completed a response, the server disconnects immediately, and a server like www.google.com always waits for the connection to be received. We need to transform the above server program to always run, the simplest way is to put the accept into a loop, then you can always receive the connection.

Maintain service

We can change the code to keep the server working:

Import socketimport sys HOST = '  # symbolic name meaning all available Interfacesport = # arbitrary Non-privileg Ed Port s = socket.socket (socket.af_inet, socket. sock_stream) print ' Socket created ' try:  s.bind ((HOST, PORT)) except Socket.error, msg:  print ' bind failed. Error Code: ' + str (msg[0]) + ' Message ' + msg[1]  sys.exit ()   print ' Socket bind complete ' S.listen (Ten) print ' Soc Ket now listening ' #now keep talking with the Clientwhile 1:  #wait to accept a connection-blocking call  Conn, ad Dr = S.accept ()  print ' Connected with ' + addr[0] + ': ' + str (addr[1])     data = Conn.recv (1024x768)  reply = ' OK. . ' + data  if not data:     break     Conn.sendall (Reply) conn.close () S.close ()

Now in a terminal running the above server program, and then open three terminals, respectively, with telnet to connect, if a terminal after the connection does not enter the data other terminals are not able to connect, and each terminal can only serve once disconnected. This can be seen from the code as well.

This is obviously not what we want, we hope that multiple clients can establish a connection at any time, and each client can communicate with the server multiple times, how to modify it?

Processing connections

In order to handle each connection, we need to separate the processing program from the receiving connection of the main program. A method can be implemented using a thread, the primary service receives the connection, creates a thread to handle the communication of the connection, and the server returns to the logic that receives the other connection.

Import socketimport sysfrom Thread import * HOST = ' # symbolic name meaning all available interfacesport = 8888 # Arbit Rary non-privileged Port s = socket.socket (socket.af_inet, socket.   SOCK_STREAM) print ' socket created ' #Bind socket to local host and Porttry:s.bind ((host, PORT)) except Socket.error, msg: print ' Bind failed. Error Code: ' + str (msg[0]) + ' Message ' + msg[1] sys.exit () print ' Socket bind complete ' #Start listening on sockets . Listen () print ' Socket now listening ' #Function for handling connections. This'll be used to create THREADSDEF Clientthread (conn): #Sending message to connected client Conn.send (' Welcome to th E server. Type something and hit enter\n ') #send only takes string #infinite loop so this function does not terminate and thread D  o not end.        While True: The #Receiving from client data = CONN.RECV (1024x768) Reply = ' OK ... ' + data if not data:break Conn.sendall (Reply) #came out of Loop conn.close () #now Keep talking With the Clientwhile 1: #wait to accept a connection-blocking call conn, addr = s.accept () print ' Connected with ' + A Ddr[0] + ': ' + str (addr[1]) #start new thread takes 1st argument as a function name to being run, second is the tuple of  Arguments to the function. Start_new_thread (Clientthread, (conn,)) S.close ()

Run the above program again, open three terminals to establish a Telnet connection with the primary server, at which time three clients can be connected, and each client can communicate with the primary server multiple times.

The following may be output under Telnet terminal:

$ telnet localhost 8888Trying 127.0.0.1...Connected to localhost. Escape character is ' ^] '. Welcome to the server. Type something and hit ENTERHIOK...HIASDOK...ASDCVOK...CV

To end the Telnet connection, press CTRL], and then enter the Close command.

The output from the server terminal might be this:

$ python server.pysocket createdsocket bind completesocket now listeningconnected with 127.0.0.1:60730connected with 127. 0.0.1:60731

So far, we have learned the basic socket programming under Python, and then there are related articles to introduce you, do not walk away.

  • 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.