PythonSocket programming tutorial

Source: Internet
Author: User
Tags telnet program
This article mainly introduces the PythonSocket programming tutorial. This article includes a client Socket programming implementation and a server Socket programming example, for more information about how to quickly learn Python Socket programming, see this document. 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.bitsCN.com in the address bar of your browser, you will open a socket, connect to www.bitsCN.com, 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:

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'

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:

The 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.bitsCN.com 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:

The 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 .bitsCN.com'

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:

The 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 .bitsCN.com'
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

The code is as follows:


$ Python client. py
Socket Created
Ip address of www.bitsCN.com is 61.145.122.155
Socket Connected to www.bitsCN.com 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:

The 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 .bitsCN.com'
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:

The 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 = 'bitscn. com ';
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: bitsCN.com \ 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:

The code is as follows:


$ Python client. py
Socket Created
Ip address of bitsCN.com is 61.145.122.
Socket Connected to bitsCN.com 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.bitsCN.com/

BitsCN.com responded 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:

The 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.bitsCN.com 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, here www.bitsCN.com is the server, and your browser is the 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:

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

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

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

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

The code is as follows:

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


What is displayed in the server window is:

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

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

The code is as follows:

$ Telnet local host 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.bitsCN.com, 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:

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

The code is as follows:

$ Telnet local host 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:

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

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

The code is as follows:

$ 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


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

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

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.