Python socket programming tutorial

Source: Internet
Author: User
Tags telnet program

  Python socket programming tutorial

[Copy link]

 
  Direct elevator

Landlord

Posted on 14:56:10| View only the author | view in reverse order

Share:
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:

  1. # Socket Client example in Python
  2. Import socket # For sockets
  3. # Create an af_inet, stream socket (TCP)
  4. S = socket. socket (socket. af_inet, socket. sock_stream)
  5. 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:

  1. # Handling errors in Python socket programs
  2. Import socket # For sockets
  3. Import sys # For exit
  4. Try:
  5. # Create an af_inet, stream socket (TCP)
  6. S = socket. socket (socket. af_inet, socket. sock_stream)
  7. Failed t socket. error, MSG:
  8. Print 'failed' to create socket. Error code: '+ STR (MSG [0]) +', error message: '+ MSG [1]
  9. SYS. Exit ();
  10. 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:

  1. Import socket # For sockets
  2. Import sys # For exit
  3. Try:
  4. # Create an af_inet, stream socket (TCP)
  5. S = socket. socket (socket. af_inet, socket. sock_stream)
  6. Failed t socket. error, MSG:
  7. Print 'failed' to create socket. Error code: '+ STR (MSG [0]) +', error message: '+ MSG [1]
  8. SYS. Exit ();
  9. Print 'socket created'
  10. Host = 'www .oschina.net'
  11. Try:
  12. Remote_ip = socket. gethostbyname (host)
  13. Failed t socket. gaierror:
  14. # Cocould not resolve
  15. Print 'hostname cocould not be resolved. existing'
  16. SYS. Exit ()
  17. 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:

  1. Import socket # For sockets
  2. Import sys # For exit
  3. Try:
  4. # Create an af_inet, stream socket (TCP)
  5. S = socket. socket (socket. af_inet, socket. sock_stream)
  6. Failed t socket. error, MSG:
  7. Print 'failed' to create socket. Error code: '+ STR (MSG [0]) +', error message: '+ MSG [1]
  8. SYS. Exit ();
  9. Print 'socket created'
  10. Host = 'www .oschina.net'
  11. Port = 80
  12. Try:
  13. Remote_ip = socket. gethostbyname (host)
  14. Failed t socket. gaierror:
  15. # Cocould not resolve
  16. Print 'hostname cocould not be resolved. existing'
  17. SYS. Exit ()
  18. Print 'IP address of '+ host + 'is' + remote_ip
  19. # Connect to remote server
  20. S. Connect (remote_ip, Port ))
  21. Print 'socket Ted CTED to '+ host + 'on ip' + remote_ip

Copy code

Run the program now

  1. $ Python client. py
  2. Socket created
  3. IP address of www.oschina.net is 61.145.122.155
  4. 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:

  1. Import socket # For sockets
  2. Import sys # For exit
  3. Try:
  4. # Create an af_inet, stream socket (TCP)
  5. S = socket. socket (socket. af_inet, socket. sock_stream)
  6. Failed t socket. error, MSG:
  7. Print 'failed' to create socket. Error code: '+ STR (MSG [0]) +', error message: '+ MSG [1]
  8. SYS. Exit ();
  9. Print 'socket created'
  10. Host = 'www .oschina.net'
  11. Port = 80
  12. Try:
  13. Remote_ip = socket. gethostbyname (host)
  14. Failed t socket. gaierror:
  15. # Cocould not resolve
  16. Print 'hostname cocould not be resolved. existing'
  17. SYS. Exit ()
  18. Print 'IP address of '+ host + 'is' + remote_ip
  19. # Connect to remote server
  20. S. Connect (remote_ip, Port ))
  21. Print 'socket Ted CTED to '+ host + 'on ip' + remote_ip
  22. # Send some data to remote server
  23. Message = "Get/HTTP/1.1 \ r \ n"
  24. Try:
  25. # Set the whole string
  26. S. sendall (Message)
  27. Failed t socket. Error:
  28. # Send failed
  29. Print 'send failed'
  30. SYS. Exit ()
  31. 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:

  1. # Socket Client example in Python
  2. Import socket # For sockets
  3. Import sys # For exit
  4. # Create an Inet, streaming socket
  5. Try:
  6. S = socket. socket (socket. af_inet, socket. sock_stream)
  7. Failed t socket. Error:
  8. Print 'failed' to create socket'
  9. SYS. Exit ()
  10. Print 'socket created'
  11. Host = 'oss. net ';
  12. Port = 80;
  13. Try:
  14. Remote_ip = socket. gethostbyname (host)
  15. Failed t socket. gaierror:
  16. # Cocould not resolve
  17. Print 'hostname cocould not be resolved. existing'
  18. SYS. Exit ()
  19. # Connect to remote server
  20. S. Connect (remote_ip, Port ))
  21. Print 'socket Ted CTED to '+ host + 'on ip' + remote_ip
  22. # Send some data to remote server
  23. Message = "Get/HTTP/1.1 \ r \ nhost: oschina.net \ r \ n"
  24. Try:
  25. # Set the whole string
  26. S. sendall (Message)
  27. Failed t socket. Error:
  28. # Send failed
  29. Print 'send failed'
  30. SYS. Exit ()
  31. Print 'message send successfully'
  32. # Now receive data
  33. Reply = S. Recv (4096)
  34. Print reply

Copy code

The following is the execution result of the above program:

  1. $ Python client. py
  2. Socket created
  3. IP address of oschina.net is 61.145.122.
  4. Socket connected to oschina.net on IP 61.145.122.155
  5. Message send successfully
  6. HTTP/1.1 301 moved permanently
  7. Server: nginx
  8. Date: Wed, 24 Oct 2012 13:26:46 GMT
  9. Content-Type: text/html
  10. Content-Length: 178
  11. Connection: keep-alive
  12. Keep-alive: timeout = 20
  13. 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:

  1. 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:

  1. Import socket
  2. Import sys
  3. Host = ''# symbolic name meaning all available Interfaces
  4. Port = 8888 # arbitrary non-privileged port
  5. S = socket. socket (socket. af_inet, socket. sock_stream)
  6. Print 'socket created'
  7. Try:
  8. S. BIND (host, Port ))
  9. Failed t socket. error, MSG:
  10. Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
  11. SYS. Exit ()
  12. 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:

  1. S. Listen (10)
  2. 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:

  1. Import socket
  2. Import sys
  3. Host = ''# symbolic name meaning all available Interfaces
  4. Port = 8888 # arbitrary non-privileged port
  5. S = socket. socket (socket. af_inet, socket. sock_stream)
  6. Print 'socket created'
  7. Try:
  8. S. BIND (host, Port ))
  9. Failed t socket. error, MSG:
  10. Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
  11. SYS. Exit ()
  12. Print 'socket bind complete'
  13. S. Listen (10)
  14. Print 'socket now listening'
  15. # Wait to accept a connection-blocking call
  16. Conn, ADDR = S. Accept ()
  17. # Display client information
  18. Print 'connectedwith' + ADDR [0] + ':' + STR (ADDR [1])

Copy code

Output
Running this program will show:

  1. $ Python server. py
  2. Socket created
  3. Socket bind complete
  4. 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:

  1. $ Telnet local host 8888
  2. It will immediately show
  3. $ Telnet local host 8888
  4. Trying 127.0.0.1...
  5. Connected to localhost.
  6. Escape Character is '^]'.
  7. Connection closed by foreign host.

Copy code

What is displayed in the server window is:

  1. $ Python server. py
  2. Socket created
  3. Socket bind complete
  4. Socket now listening
  5. 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:

  1. Import socket
  2. Import sys
  3. Host = ''# symbolic name meaning all available Interfaces
  4. Port = 8888 # arbitrary non-privileged port
  5. S = socket. socket (socket. af_inet, socket. sock_stream)
  6. Print 'socket created'
  7. Try:
  8. S. BIND (host, Port ))
  9. Failed t socket. error, MSG:
  10. Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
  11. SYS. Exit ()
  12. Print 'socket bind complete'
  13. S. Listen (10)
  14. Print 'socket now listening'
  15. # Wait to accept a connection-blocking call
  16. Conn, ADDR = S. Accept ()
  17. Print 'connectedwith' + ADDR [0] + ':' + STR (ADDR [1])
  18. # Now keep talking with the client
  19. Data = conn. Recv (1024)
  20. Conn. sendall (data)
  21. Conn. Close ()
  22. S. Close ()

Copy code

Continue to run the above code, and then open another command line window and enter the following command:

  1. $ Telnet local host 8888
  2. Trying 127.0.0.1...
  3. Connected to localhost.
  4. Escape Character is '^]'.
  5. Happy
  6. Happy
  7. 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:

  1. Import socket
  2. Import sys
  3. Host = ''# symbolic name meaning all available Interfaces
  4. Port = 8888 # arbitrary non-privileged port
  5. S = socket. socket (socket. af_inet, socket. sock_stream)
  6. Print 'socket created'
  7. Try:
  8. S. BIND (host, Port ))
  9. Failed t socket. error, MSG:
  10. Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
  11. SYS. Exit ()
  12. Print 'socket bind complete'
  13. S. Listen (10)
  14. Print 'socket now listening'
  15. # Now keep talking with the client
  16. While 1:
  17. # Wait to accept a connection-blocking call
  18. Conn, ADDR = S. Accept ()
  19. Print 'connectedwith' + ADDR [0] + ':' + STR (ADDR [1])
  20. Data = conn. Recv (1024)
  21. Reply = 'OK...' + Data
  22. If not data:
  23. Break
  24. Conn. sendall (reply)
  25. Conn. Close ()
  26. 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:

  1. $ Telnet local host 5000
  2. Trying 127.0.0.1...
  3. Connected to localhost.
  4. Escape Character is '^]'.
  5. Happy
  6. OK .. happy
  7. Connection closed by foreign host.

Copy code

The terminal window of the server is displayed as follows:

  1. $ Python server. py
  2. Socket created
  3. Socket bind complete
  4. Socket now listening
  5. Connected with 127.0.0.1: 60225
  6. Connected with 127.0.0.1: 60237
  7. 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:

  1. Import socket
  2. Import sys
  3. From thread import *
  4. Host = ''# symbolic name meaning all available Interfaces
  5. Port = 8888 # arbitrary non-privileged port
  6. S = socket. socket (socket. af_inet, socket. sock_stream)
  7. Print 'socket created'
  8. # Bind socket to local host and Port
  9. Try:
  10. S. BIND (host, Port ))
  11. Failed t socket. error, MSG:
  12. Print 'Bind failed. Error code: '+ STR (MSG [0]) + 'message' + MSG [1]
  13. SYS. Exit ()
  14. Print 'socket bind complete'
  15. # Start listening on socket
  16. S. Listen (10)
  17. Print 'socket now listening'
  18. # Function for handling connections. This will be used to create threads
  19. Def clientthread (conn ):
  20. # Sending message to connected Client
  21. Conn. Send ('Welcome to the server. Type something and hit enter \ n') # Send only takes string
  22. # Infinite loop so that function do not terminate and thread do not end.
  23. While true:
  24. # Grouping from client
  25. Data = conn. Recv (1024)
  26. Reply = 'OK...' + Data
  27. If not data:
  28. Break
  29. Conn. sendall (reply)
  30. # Came out of Loop
  31. Conn. Close ()
  32. # Now keep talking with the client
  33. While 1:
  34. # Wait to accept a connection-blocking call
  35. Conn, ADDR = S. Accept ()
  36. Print 'connectedwith' + ADDR [0] + ':' + STR (ADDR [1])
  37. # Start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
  38. Start_new_thread (clientthread, (Conn ,))
  39. S. Close ()

Copy code

Run the preceding server program, open three terminal windows as before, and execute the Telent command:

  1. $ Telnet local host 8888
  2. Trying 127.0.0.1...
  3. Connected to localhost.
  4. Escape Character is '^]'.
  5. Welcome to the server. Type something and hit Enter
  6. Hi
  7. OK... hi
  8. ASD
  9. OK... ASD
  10. CV
  11. OK... CV

Copy code

The output information of the terminal window where the server is located is as follows:

  1. $ Python server. py
  2. Socket created
  3. Socket bind complete
  4. Socket now listening
  5. Connected with 127.0.0.1: 60730
  6. 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.

 
   
   

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.