Python Socket network programming

Source: Internet
Author: User
Tags localhost 8888

Python Socket network programming
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 the server: to create a socket for client programming, you must first create a socket. You can 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 'function Socket. the socket creates a socket and returns the socket descriptor, which will be used in subsequent functions. This function has two parameters: Address Family: AF_INET (for interprocess communication over the Internet) or AF_UNIX (for interprocess communication between the same machine) Type: socket Type, it 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, therefore, the relevant function parameters and return values will not be described in detail. If you need to know more, you can view the relevant manual for error handling. If the socket function fails to be created, a socket will be thrown. error exception, need to capture: # handling errors in python socket programs import socket # for socketsimport sys # for exit try: # create an AF_INET, STR EAM socket (TCP) s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) Doesn't 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. 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) failed t socket. gaierror: # cocould not resolve print 'hostname cocould not be resolved. exiting 'sys. exit () print 'IP address of '+ host + 'is' + remote_ip now we know the Ip address of the server, you can use the connect function to Connect to a specific port of the IP address. In the following example, connect to port 80 (the default port of the HTTP Service): # Connect to r Emote servers. connect (remote_ip, port) print 'socket Connected to '+ host + 'on ip' + remote_ip to 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 the above indicates that the connection to www.google.com has been successful. Next we can send some data to the server, for example, send a string GET/HTTP/1.1 \ r \ n, which is a command for HTTP request webpage content. # Send some data to remote servermessage = "GET/HTTP/1.1 \ r \ n" try: # Set the whole string s. sendall (message) handle T socket. error: # Send failed print 'send failed' sys. exit () print 'message send successfully 'after the data is sent, the client also needs to accept the server response. The receiving data function recv can be used to receive socket data: # Now receive datareply = s. the result of running recv (4096) print reply together is as follows: Socket createdIp of remote host www.google.com is 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: 262 Date: 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 the socket. When we do not want to request server data again, we can disable the socket to end the communication: s. close () summary we learned how to: create a socket to connect to the remote server to send data to receive data close socket when we open www.google.com, the browser does this, knowing this is very 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. Programming on the server side mainly does the following work: Open the socket and bind it to a specific address and listen on the port to establish a connection to receive/send data. The above describes how to create a socket, the following step is binding. The bind function of the socket binding function can be used to bind the 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) blocks t 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 next step is to listen for the connection. The listener connection function listen 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. 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 'ted CTED with '+ addr [0] +': '+ str (addr [1]) to run the program. The output result 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 8888 Trying 127.0.0.1... connected to localhost. escape character is '^]'. connection closed by foreign host. at this time, the server output will show: $ python server. pySocket createdSocket bind completeSocket now listeningConnected with 127.0.0.1: 59954 we can see that the client has been 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) blocks t socket. error, msg: print 'Bind failed. error Code: '+ str (msg [0]) + 'message' + msg [1] sys. exit () print 'so Cket bind complete's. listen (10) print 'socket now listening '# wait to accept a connection-blocking callconn, addr = s. accept () print 'connectedwith' + addr [0] + ':' + str (addr [1]) # now keep talking with the clientdata = conn. recv (1, 1024) conn. sendall (data) conn. close () s. close () runs this program on one terminal, opens another terminal, and uses telnet to connect to the server. If you enter a string, you will see: $ telnet localhost 8888 Trying 127.0.0.1... connected to localhost. escap E 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. To maintain the service, we can change the code to make the Server Always work: 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) blocks 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 clientwhile 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 () now runs the above server program under a terminal, and then starts three terminals, respectively using telnet to connect, if a terminal cannot be connected without data input, and 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? Processing connection in order 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) blocks t socket. error, msg: print 'Bind failed. error Code: '+ str (msg [0]) + 'message' + msg [1] sys. exit () print's Ocket 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: # Rece Iving 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 '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 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, in addition, each client can communicate with the master server multiple times. The telnet terminal may output the following: $ telnet localhost 8888 Trying 127.0.0.1... connected to localhost. escape character is '^]'. welcome to the server. type something and hit enterhiOK... hiasdOK... asdcvOK... to end the telnet connection, press Ctrl-] And then enter the close command. The output of the server terminal may be like this: $ python server. pySocket createdSocket bind completeSocket now listeningConnected with 127.0.0.1: 60730 Connected with 127.0.0.1: 60731

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.