Python Socket programming tutorial, pythonsocket

Source: Internet
Author: User
Tags localhost 8888 telnet program

Python Socket programming tutorial, pythonsocket

This is a guide and tutorial for quickly learning Python Socket programming. The Socket programming in Python is similar to that in C.
Python about Socket functions please 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.jb51.net in the address bar of your browser, you will open a socket, connect to www.jb51.net, read the response page, and display it. Other chat clients, such as gtalk and skype, are similar. Any network communication is completed through Socket.

Start

This tutorial assumes that you already have some basic Python programming knowledge.
Let's start Socket programming.

Create Socket

The first thing to do is to create a Socket, which can be implemented by the socket function. The Code is as follows:

Copy codeThe 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'

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:
Copy codeThe Code is as follows:
# 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'

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 server

The server address and port number are required to connect to the server. Here, port www.jb51.net and port 80 are used.

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:

Copy codeThe Code is as follows:
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 .jb51.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

We already have an IP address. Next we need to specify the port to connect.
Code:

Copy codeThe Code is as follows:
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 .jb51.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

Run the program now
Copy codeThe Code is as follows:
$ Python client. py
Socket Created
Ip address of www.jb51.net is 61.145.122.155
Socket Connected to www.jb51.net on ip 61.145.122.155

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.

Reminder

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:
Copy codeThe Code is as follows:
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 .jb51.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'

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 data

The recv function is used to receive data from the socket:
Copy codeThe Code is as follows:
# 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 = 'jb51. 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: jb51.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

The following is the execution result of the above program:
Copy codeThe Code is as follows:
$ Python client. py
Socket Created
Ip address of jb51.net is 61.145.122.
Socket Connected to jb51.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.bkjia.com/

Jb51.net responds to the URL content we requested, which is very simple. After receiving the data, you can close the Socket.

Disable socket

The close function is used to close the Socket:
Copy codeThe Code is as follows: s. close ()
That's it.

Let's review

In 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.jb51.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. Therefore, www.jb51.net is a server, and your browser is a client.
Next we start to code the node on the server.

Server programming

Server 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 Socket

The 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:
Copy codeThe Code is as follows:
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'

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 listening

After 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:
Copy codeThe Code is as follows:
S. listen (10)
Print 'socket now listening'

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 connection
Sample Code:
Copy codeThe Code is as follows:
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])

Output
Running this program will show:
Copy codeThe Code is as follows: $ python server. py
Socket created
Socket bind complete
Socket now listening

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:
Copy codeThe Code is as follows: $ telnet localhost 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.
What is displayed in the server window is:
Copy codeThe Code is as follows: $ python server. py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1: 59954

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:
Copy codeThe Code is as follows:
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 ()

Continue to run the above code, and then open another command line window and enter the following command:
Copy codeThe Code is as follows: $ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Happy
Happy
Connection closed by foreign host.

The client receives the response from the server.
The above example is the same. The server immediately exits after responding. Some real servers, such as www.jb51.net, are always running and accept connection requests.
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 running

Slightly changed the above Code:
Copy codeThe Code is as follows:
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 ()

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:
Copy codeThe Code is as follows: $ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Happy
OK .. happy
Connection closed by foreign host.
The terminal window of the server is displayed as follows:
Copy codeThe Code is 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
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 connections

To 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:
Copy codeThe Code is as follows: 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 ()

Run the preceding server program, open three terminal windows as before, and execute the telent command:
Copy codeThe Code is as follows: $ telnet localhost 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
The output information of the terminal window where the server is located is as follows:
Copy codeThe Code 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
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.


Python socket programming questions

Your example is okay.
While 1:
This section is an infinite loop.
As long as the client (the browser) and server (your program) still communicate, the while loop will not end.

So what you see is the effect of getting stuck, because the server is always waiting to receive data from the client.

Therefore, this while loop exits only when the server program is forcibly disabled.

Generally, if you want to send a long request to the server, you need some way to indicate the length of your data, one is the Unique End-of-string Identifier (that is, the End mark of the string, at the end of the data), one is the Size Indicator (tell the server how long your data is at the beginning of the data)

It is recommended that you carefully read the relevant documents or book pull, which is hard to explain here.

Python network programming basics are recommended:
Www.douban.com/subject/1097490/
The English version can be taken from my online storage:
Dl.getdropbox.com/..g.djvu

Socket programming for python

Wait. After sending, an end sign is sent. In fact, sending length in advance is the simplest and most effective method.

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.