Python Socket network programming, pythonsocket

Source: Internet
Author: User
Tags localhost 8888

Python Socket network programming, pythonsocket

Socket is a method of inter-process communication. It communicates with other processes mainly in different ways: it can implement inter-process communication between different hosts, most of our various services on the network communicate based on sockets, such as Browsing webpages, chatting via QQ, sending and receiving emails, etc. To solve the process communication problem between two hosts on the network, you must first uniquely identify the process. In the TCP/IP network protocol, it is through (IP address, protocol, port number) to identify a process by using the productkey, devicename, and devicesecret.

This article mainly introduces TCP Socket network programming using Python. assume that you have a preliminary knowledge about the network and basic Python syntax.

TCP is a connection-oriented transport layer protocol. TCP Socket is based on a Client-Server programming model. The Server listens to Client connection requests. Once a connection is established, data can be transmitted. The introduction to TCP Socket programming is also divided into the client and server:

I. Client Programming
Create socket

First, create a socket. Use the socket function socket of the socket module in Python to complete the process:

#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 will be used in subsequent functions. This function has two parameters:

Address Family: You can select AF_INET for interprocess communication over the Internet or AF_UNIX for interprocess communication between the same machine)
Type: socket Type, which can be SOCKET_STREAM (stream socket, mainly used for TCP protocol) or SOCKET_DGRAM (datagram socket, mainly used for UDP Protocol)
Note: This article mainly describes the Python Socket programming process, so we will not detail the related function parameters and return values. For more information, see the relevant manual.

Error Handling

If the socket function fails to be created, a socket. error exception is thrown, which must 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. Next we will use this socket to connect to a server, even www.google.com.

Connect to the server

This article also mentioned that socket uses (IP address, protocol, Port Number) to identify a process. 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 = 80 try:  remote_ip = socket.gethostbyname( host ) except socket.gaierror:  #could not resolve  print 'Hostname could not be resolved. Exiting'  sys.exit()   print 'Ip address of ' + host + ' is ' + remote_ip

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

#Connect to remote servers.connect((remote_ip , port)) print 'Socket 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 www.google.com has been successful. Next we can send some data to the server, such as sending the string GET/HTTP/1.1 \ r \ n, this is an HTTP request for webpage content.

#Send some data to remote servermessage = "GET / HTTP/1.1\r\n\r\n" try :  #Set the whole string  s.sendall(message)except socket.error:  #Send failed  print 'Send failed'  sys.exit() print 'Message send successfully'

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

Receive data

The recv function can be used to receive socket data:

#Now receive datareply = s.recv(4096) print reply

The running results 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.145Message 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, 11 Dec 2014 08:47:58 GMTServer: GFE/2.0Alternate-Protocol: 80:quic,p=0.02<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"><TITLE>302 Moved</TITLE></HEAD><BODY><H1>302 Moved</H1>The document has moved<A HREF="http://www.google.com.sg/?gfe_rd=cr&ei=PlqJVLCREovW8gfF0oG4CQ">here</A>.</BODY></HTML>

Disable socket

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

S. close ()
Summary

We learned how:

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

What the browser does when we open www.google.com is meaningful. A client with such behavior characteristics in a socket is called a CLIENT, which connects to a remote system to obtain data.

Another behavior in socket is called SERVER. The SERVER uses socket to receive connections and provide data, which is the opposite of the client. Therefore, www.google.com is a server, your browser is a client, or, more accurately, www.google.com is an HTTP server, and your browser is an HTTP client.

So the client programming is introduced above. Now it's the server's turn to use socket.

Ii. server-side Programming
The server mainly performs the following tasks:

  • Open socket
  • Bind to a specific address and port
  • Listen for connection
  • Establish a connection
  • Receive/send data

The preceding section describes how to create a socket. The following section describes how to bind a socket.

Bind a socket

The bind function can be used to bind a socket to a specific address and port. It requires a sockaddr_in structure as the parameter:

import socketimport sys HOST = ''  # Symbolic name meaning all available interfacesPORT = 8888 # Arbitrary non-privileged 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 listener is connected.

Listen for connection

The listen function can place the socket in the listening mode:

s.listen(10)print 'Socket now listening'

This function has a parameter called backlog, which is used to control the number of connections. If it is set to 10, 10 connections are waiting for processing. At this time, 11th requests 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 ' + addr[0] + ':' + str(addr[1])

The output result of running the program is as follows:

$ python server.pySocket createdSocket bind completeSocket now listening

At this time, the program waits for the request to arrive on port 8888. Do not close this program and keep it running. Now the client can connect to the socket through this port. We use the telnet client to test, open a terminal, and enter telnet localhost 8888:

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

The server output will display:

$ python server.pySocket createdSocket bind completeSocket now listeningConnected with 127.0.0.1:59954

We can see that the client is connected to the server. After the connection is established, we can use it to communicate with the client. The following example demonstrates that after the server establishes a connection, it receives the data sent by the client and immediately sends the data back. The following is a complete server program:

import socketimport sys HOST = ''  # Symbolic name meaning all available interfacesPORT = 8888 # Arbitrary non-privileged 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(10)print 'Socket 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(1024)conn.sendall(data) conn.close()s.close()

Run this program on one terminal, open another terminal, connect to the server via telnet, and enter the string as needed. You will see:

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

The client (telnet) receives the server response.

After a response is completed, the server immediately disconnects, and servers such as www.google.com are always waiting to receive connections. We need to transform the above server program to keep running, the simplest way is to put the accept in a loop, then we can always receive connections.

Maintain Service

We can change the code to this to keep the server working:

import socketimport sys HOST = ''  # Symbolic name meaning all available interfacesPORT = 5000 # Arbitrary non-privileged 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(10)print 'Socket now listening' #now keep talking with the clientwhile 1:  #wait to accept a connection - blocking call  conn, addr = s.accept()  print 'Connected with ' + addr[0] + ':' + str(addr[1])     data = conn.recv(1024)  reply = 'OK...' + data  if not data:     break     conn.sendall(reply) conn.close()s.close()

Now, you can run the preceding server program in one terminal, and then start three terminals to connect with them via telnet. If one terminal is connected without entering data, other terminals cannot connect, in addition, each terminal can only be disconnected once. This can also be seen from the code.

This is obviously not what we want. We hope that multiple clients can establish connections at any time, and each client can communicate with the Server Multiple times. How can we modify this?

Process connections

To process each connection, we need to separate the processing program from the receiving connection of the main program. One method can be implemented using a thread. The main service program receives a connection, creates a thread to process the communication of the connection, and then the server returns to the logic of receiving other connections.

import socketimport sysfrom thread import * HOST = ''  # Symbolic name meaning all available interfacesPORT = 8888 # Arbitrary 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(10)print 'Socket now listening' #Function for handling connections. This will be used to create threadsdef 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:         #Receiving 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 clientwhile 1:  #wait to accept a connection - blocking call  conn, addr = s.accept()  print 'Connected with ' + 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 above program again and open three terminals to establish a telnet connection with the master server. At this time, the three clients can be connected at any time, and each client can communicate with the master server multiple times.

The telnet terminal may output the following output:

$ 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 of the server terminal may be as follows:

$ 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 in Python, and there will be related articles to you later. Don't go away.

Articles you may be interested in:
  • Python network programming (Socket sends messages)
  • Python socket network programming steps (socket used)
  • Python network programming-Example of TCP communication instance and socketserver framework
  • Python network programming learning notes (2): Establish a network client through socket
  • Python Network Programming Study Notes (III): socket network server
  • Python Network Programming Study Notes (5): Supplement to socket

Related Article

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.