This is a guide and tutorial for quickly learning Python socket programming. The socket programming in python is similar to that in C. For more information about the socket functions of Python, see Http://docs.python.org/library/socket.html
Basically, socket is the most basic content in any computer network communication. For example, when you enter Www.oschina.net, you will open a socket and connect Www.oschina.net, read the response page, and then display it. Other chat clients, such as Gtalk and Skype, are similar. Any network communication is completed through socket.
StartThis tutorial assumes that you already have some basic Python programming knowledge. Let's start socket programming. Create socketThe first thing to do is to create a socket, which can be implemented by the socket function. The Code is as follows:
- # Socket Client example in Python
- Import socket # For sockets
- # Create an af_inet, stream socket (TCP)
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Print 'socket created'
Copy code The socket. socket function creates a socket and returns the socket descriptor which can be used by other socket-related functions. The above Code uses the following two attributes to create a socket: Address cluster: af_inet (IPv4) Type: sock_stream (using TCP transmission control protocol) Error Handling If the socket function fails, python will throw an exception named socket. error, which must be handled:
- # Handling errors in Python socket programs
- Import socket # For sockets
- Import sys # For exit
- Try:
- # Create an af_inet, stream socket (TCP)
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Failed t socket. error, MSG:
- Print 'failed' to create socket. Error code: '+ STR (MSG [0]) +', error message: '+ MSG [1]
- SYS. Exit ();
- Print 'socket created'
Copy code Now, if you have successfully created a socket, what should you do next? Next we will use this socket to connect to the server. Note: Other types corresponding to sock_stream are sock_dgram used for UDP communication protocol. UDP communication is not a socket connection. In this article, we will only discuss sock_stream or TCP.
Connect to the serverThe server address and port number are required to connect to the server. Www.oschina.net and port 80. First, obtain the IP address of the remote host. Before connecting to a remote host, we need to know its IP address. In python, getting an IP address is simple:
- Import socket # For sockets
- Import sys # For exit
- Try:
- # Create an af_inet, stream socket (TCP)
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Failed t socket. error, MSG:
- Print 'failed' to create socket. Error code: '+ STR (MSG [0]) +', error message: '+ MSG [1]
- SYS. Exit ();
- Print 'socket created'
- Host = 'www .oschina.net'
- Try:
- Remote_ip = socket. gethostbyname (host)
- Failed t socket. gaierror:
- # Cocould not resolve
- Print 'hostname cocould not be resolved. existing'
- SYS. Exit ()
- Print 'IP address of '+ host + 'is' + remote_ip
Copy code We already have an IP address. Next we need to specify the port to connect. Code:
- Import socket # For sockets
- Import sys # For exit
- Try:
- # Create an af_inet, stream socket (TCP)
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Failed t socket. error, MSG:
- Print 'failed' to create socket. Error code: '+ STR (MSG [0]) +', error message: '+ MSG [1]
- SYS. Exit ();
- Print 'socket created'
- Host = 'www .oschina.net'
- Port = 80
- Try:
- Remote_ip = socket. gethostbyname (host)
- Failed t socket. gaierror:
- # Cocould not resolve
- Print 'hostname cocould not be resolved. existing'
- SYS. Exit ()
- Print 'IP address of '+ host + 'is' + remote_ip
- # Connect to remote server
- S. Connect (remote_ip, Port ))
- Print 'socket Ted CTED to '+ host + 'on ip' + remote_ip
Copy code Run the program now
- $ Python client. py
- Socket created
- IP address of www.oschina.net is 61.145.122.155
- Socket connected to www.oschina.net on IP 61.145.122.155
Copy code This program creates a socket and connects to it. How can I use other non-existent ports (such as 81? This logic is equivalent to building a port scanner. The connection is connected, and the next step is to send data to the server. Free tips The concept of "connection" is available only when sock_stream/TCP socket is used. Connection means reliable data stream communication mechanism, which can have multiple data streams at the same time. It can be imagined as a pipe where data does not interfere with each other. Another important note is that data packets are sent and received sequentially.
Some other sockets, such as UDP, ICMP, and ARP, do not have a "connection" concept. They are connectionless communication, meaning that you can send and receive packets from anyone or to anyone. Send data The sendall function is used to send data in a simple way. We can send some data to oschina:
- Import socket # For sockets
- Import sys # For exit
- Try:
- # Create an af_inet, stream socket (TCP)
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Failed t socket. error, MSG:
- Print 'failed' to create socket. Error code: '+ STR (MSG [0]) +', error message: '+ MSG [1]
- SYS. Exit ();
- Print 'socket created'
- Host = 'www .oschina.net'
- Port = 80
- Try:
- Remote_ip = socket. gethostbyname (host)
- Failed t socket. gaierror:
- # Cocould not resolve
- Print 'hostname cocould not be resolved. existing'
- SYS. Exit ()
- Print 'IP address of '+ host + 'is' + remote_ip
- # Connect to remote server
- S. Connect (remote_ip, Port ))
- Print 'socket Ted CTED to '+ host + 'on ip' + remote_ip
- # Send some data to remote server
- Message = "Get/HTTP/1.1 \ r \ n"
- Try:
- # Set the whole string
- S. sendall (Message)
- Failed t socket. Error:
- # Send failed
- Print 'send failed'
- SYS. Exit ()
- Print 'message send successfully'
Copy code In the preceding example, connect to the target server and then send the string data "Get/HTTP/1.1 \ r \ n". This is an HTTP command, used to obtain the content of the homepage.
Next, you need to read the data returned by the server. Receive dataThe Recv function is used to receive data from the socket:
- # Socket Client example in Python
- Import socket # For sockets
- Import sys # For exit
- # Create an Inet, streaming socket
- Try:
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Failed t socket. Error:
- Print 'failed' to create socket'
- SYS. Exit ()
- Print 'socket created'
- Host = 'oss. net ';
- Port = 80;
- Try:
- Remote_ip = socket. gethostbyname (host)
- Failed t socket. gaierror:
- # Cocould not resolve
- Print 'hostname cocould not be resolved. existing'
- SYS. Exit ()
- # Connect to remote server
- S. Connect (remote_ip, Port ))
- Print 'socket Ted CTED to '+ host + 'on ip' + remote_ip
- # Send some data to remote server
- Message = "Get/HTTP/1.1 \ r \ nhost: oschina.net \ r \ n"
- Try:
- # Set the whole string
- S. sendall (Message)
- Failed t socket. Error:
- # Send failed
- Print 'send failed'
- SYS. Exit ()
- Print 'message send successfully'
- # Now receive data
- Reply = S. Recv (4096)
- Print reply
Copy code The following is the execution result of the above program:
- $ Python client. py
- Socket created
- IP address of oschina.net is 61.145.122.
- Socket connected to oschina.net on IP 61.145.122.155
- Message send successfully
- HTTP/1.1 301 moved permanently
- Server: nginx
- Date: Wed, 24 Oct 2012 13:26:46 GMT
- Content-Type: text/html
- Content-Length: 178
- Connection: keep-alive
- Keep-alive: timeout = 20
- Location: http://www.oschina.net/
Copy code Oschina.net responded to the URL content we requested, which is very simple. After receiving the data, you can close the socket. Disable socketThe close function is used to close the socket:
- S. Close ()
Copy code That's it. Let's reviewIn the above example, we learned how: 1. Create a socket 2. Connect to the remote server 3. Send data 4. Receive response When you open www.oschina.net in a browser, the process is the same. There are two types: client and server. The client connects to the server and reads data. The server uses Socket to receive incoming connections and provide data. So here Www.oschina.net is the server, and your browser is the client.
Next we start to code the node on the server. Server programmingServer programming mainly includes the following steps: 1. Open socket 2. bind to an address and port 3. Listen for incoming connections 4. Accept connections 5. Read and Write Data We have learned how to open the socket. The following is the binding to the specified address and port. Bind a socketThe BIND function is used to bind a socket to a specific address and port. It requires a addr_in struct similar to that required by the connect function.
Sample Code:
- Import socket
- Import sys
- Host = ''# symbolic name meaning all available Interfaces
- Port = 8888 # arbitrary non-privileged port
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Print 'socket created'
- Try:
- S. BIND (host, Port ))
- Failed t socket. error, MSG:
- Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
- SYS. Exit ()
- Print 'socket bind complete'
Copy code After the connection is bound, the socket needs to start listening for the connection. Obviously, you cannot bind two different sockets to the same port. Connection listeningAfter the socket is bound, you can start listening for the connection. We need to change the socket to the listening mode. The listen function of socket is used to implement the listening mode:
- S. Listen (10)
- Print 'socket now listening'
Copy code The parameter required by the listen function is backlog, which is used to control the number of connections that can remain in the waiting state when the program is busy. Here we pass 10, which means that if 10 connections are waiting for processing, the 11th connections will be rejected. This is clearer when socket_accept is checked.
Accept connectionSample Code:
- Import socket
- Import sys
- Host = ''# symbolic name meaning all available Interfaces
- Port = 8888 # arbitrary non-privileged port
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Print 'socket created'
- Try:
- S. BIND (host, Port ))
- Failed t socket. error, MSG:
- Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
- SYS. Exit ()
- Print 'socket bind complete'
- S. Listen (10)
- Print 'socket now listening'
- # Wait to accept a connection-blocking call
- Conn, ADDR = S. Accept ()
- # Display client information
- Print 'connectedwith' + ADDR [0] + ':' + STR (ADDR [1])
Copy code Output Running this program will show:
- $ Python server. py
- Socket created
- Socket bind complete
- Socket now listening
Copy code Now this program starts to wait for the connection to enter. The port is 8888. Please do not close this program. We will use the telnet program for testing. Open the command line window and enter:
- $ Telnet local host 8888
- It will immediately show
- $ Telnet local host 8888
- Trying 127.0.0.1...
- Connected to localhost.
- Escape Character is '^]'.
- Connection closed by foreign host.
Copy code What is displayed in the server window is:
- $ Python server. py
- Socket created
- Socket bind complete
- Socket now listening
- Connected with 127.0.0.1: 59954
Copy code We can see that the client has been successfully connected to the server. In the above example, we receive the connection and close it immediately. Such a program has no practical value. After the connection is established, there will usually be a lot of things to deal, so let's make a response to the client. The sendall function can send data to the client through socket:
- Import socket
- Import sys
- Host = ''# symbolic name meaning all available Interfaces
- Port = 8888 # arbitrary non-privileged port
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Print 'socket created'
- Try:
- S. BIND (host, Port ))
- Failed t socket. error, MSG:
- Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
- SYS. Exit ()
- Print 'socket bind complete'
- S. Listen (10)
- Print 'socket now listening'
- # Wait to accept a connection-blocking call
- Conn, ADDR = S. Accept ()
- Print 'connectedwith' + ADDR [0] + ':' + STR (ADDR [1])
- # Now keep talking with the client
- Data = conn. Recv (1024)
- Conn. sendall (data)
- Conn. Close ()
- S. Close ()
Copy code Continue to run the above code, and then open another command line window and enter the following command:
- $ Telnet local host 8888
- Trying 127.0.0.1...
- Connected to localhost.
- Escape Character is '^]'.
- Happy
- Happy
- Connection closed by foreign host.
Copy code The client receives the response from the server. The above example is the same. The server immediately exits after responding. And some real server Images Www.oschina.net is always running and receives connection requests at any time. That is to say, the server should always be running; otherwise, it cannot be a "service". Therefore, to keep the server running, the simplest way is to put the accept method in a loop. Servers that have been runningSlightly changed the above Code:
- Import socket
- Import sys
- Host = ''# symbolic name meaning all available Interfaces
- Port = 8888 # arbitrary non-privileged port
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Print 'socket created'
- Try:
- S. BIND (host, Port ))
- Failed t socket. error, MSG:
- Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
- SYS. Exit ()
- Print 'socket bind complete'
- S. Listen (10)
- Print 'socket now listening'
- # Now keep talking with the client
- While 1:
- # Wait to accept a connection-blocking call
- Conn, ADDR = S. Accept ()
- Print 'connectedwith' + ADDR [0] + ':' + STR (ADDR [1])
- Data = conn. Recv (1024)
- Reply = 'OK...' + Data
- If not data:
- Break
- Conn. sendall (reply)
- Conn. Close ()
- S. Close ()
Copy code Simply add a while 1 Statement. Continue to run the server, and then open the other three command line windows. Each window uses the Telnet command to connect to the server:
- $ Telnet local host 5000
- Trying 127.0.0.1...
- Connected to localhost.
- Escape Character is '^]'.
- Happy
- OK .. happy
- Connection closed by foreign host.
Copy code The terminal window of the server is displayed as follows:
- $ Python server. py
- Socket created
- Socket bind complete
- Socket now listening
- Connected with 127.0.0.1: 60225
- Connected with 127.0.0.1: 60237
- Connected with 127.0.0.1: 60239
Copy code You can see that the server will no longer quit. Okay, use Ctrl + C to close the server. All Telnet terminals will display "Connection closed by foreign host ."
This communication efficiency is too low. The server program uses loops to accept connections and send responses. This is equivalent to processing a client request at most at a time, however, we require the server to process multiple requests at the same time. Process multiple connectionsTo process multiple connections, we need an independent processing code to run when the master server receives the connection. One way is to use a thread. The server receives the connection and creates a thread to process the connection and send and receive data. Then, the master server program returns to receive the new connection.
Here we use threads to process connection requests:
- Import socket
- Import sys
- From thread import *
- Host = ''# symbolic name meaning all available Interfaces
- Port = 8888 # arbitrary non-privileged port
- S = socket. socket (socket. af_inet, socket. sock_stream)
- Print 'socket created'
- # Bind socket to local host and Port
- Try:
- S. BIND (host, Port ))
- Failed t socket. error, MSG:
- Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
- SYS. Exit ()
- Print 'socket bind complete'
- # Start listening on socket
- S. Listen (10)
- Print 'socket now listening'
- # Function for handling connections. This will be used to create threads
- Def clientthread (conn ):
- # Sending message to connected Client
- Conn. Send ('Welcome to the server. Type something and hit enter \ n') # Send only takes string
- # Infinite loop so that function do not terminate and thread do not end.
- While true:
- # Grouping from client
- Data = conn. Recv (1024)
- Reply = 'OK...' + Data
- If not data:
- Break
- Conn. sendall (reply)
- # Came out of Loop
- Conn. Close ()
- # Now keep talking with the client
- While 1:
- # Wait to accept a connection-blocking call
- Conn, ADDR = S. Accept ()
- Print 'connectedwith' + ADDR [0] + ':' + STR (ADDR [1])
- # Start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
- Start_new_thread (clientthread, (Conn ,))
- S. Close ()
Copy code Run the preceding server program, open three terminal windows as before, and execute the Telent command:
- $ Telnet local host 8888
- Trying 127.0.0.1...
- Connected to localhost.
- Escape Character is '^]'.
- Welcome to the server. Type something and hit Enter
- Hi
- OK... hi
- ASD
- OK... ASD
- CV
- OK... CV
Copy code The output information of the terminal window where the server is located is as follows:
- $ Python server. py
- Socket created
- Socket bind complete
- Socket now listening
- Connected with 127.0.0.1: 60730
- Connected with 127.0.0.1: 60731
Copy code The thread takes over the connection and returns the corresponding data to the client. This is the Server programming we will introduce. Conclusion So far, you have learned the basic programming of Python socket. You can compile some examples by yourself to enhance this knowledge. You may encounter some problems: bind failed. Error code: 98 Message address already in use. To solve this problem, you only need to change the server port. |