Python network programming, TCP/IP client and server, 2015 python

Source: Internet
Author: User

Python network programming, TCP/IP client and server, 2015 python

I have never been very clear about the definition of the server, and I have only a vague feeling about what the server/client architecture is. I recently started to learn about the relationship between some servers and clients.

A server is a service provider. It is a hardware or software that can provide the required services to one or more clients. Its purpose is to wait for the customer's request, then serve the customer, and then wait for the request.

The client connects to a server, initiates its own request, and waits for feedback.

For example, a printer is an example of a server, and a computer connected to it is a client. After a printer is connected over the network, the printer is asked to print and transmit data (transmitted content ), then the printer starts to work, or returns the cause of service failure (such as paper shortage or no ink). The printer is on the server side, waiting for a request, and it is always working, the computer is a client, and it does not work only.

A printer is a hardware server with some software servers, such as Web servers and database servers.

-----------------------------------------------------------------------------

So how are they connected through the network? How does client/server network programming work?

First, we need to create a communication power-off so that the server can "listen" requests, such as the company's phone number. The customer issues requests to the company through telephone devices.

Of course, a server must send its own phone number to a potential customer to receive a response. That is to say, it must send the website address to the customer.

The client also creates a communication endpoint and establishes a connection with the server. Then, the customer can make a request.

Bytes -------------------------------------------------------------------------------------

The concept of a communication endpoint is called socket.

The concept of "Communication endpoint" we talked about earlier is an abstraction of communication, and socket is a data structure with such capabilities.

Just like using the integer floating-point Boolean Type, socket is also a data structure through which we can access the network.

Socket originated in the 1970s s and was created on Unix at the University of California, Berkeley. It was initially designed for communications between multiple applications on the same machine, there are two types of inter-process communication: file system and network.

It is meaningful to use a file system for communication between different processes, because the file system can be accessed by different processes. Network-based sockets are required for different computers.

First, I only consider network-based sockets. There are two address families: AF_INET and AF_NETLINK. Most of the time, we are talking about AF_INET sockets with links.

 

The socket address consists of two parts: Host and port.

Similar to the area code and phone number of a telephone network. The host determines the machine you are accessing, that is, an IP address. The port is the port number used by the server software you are accessing. A machine can have many programs using ports. Valid port numbers range from 0 ~ 65535. A port number smaller than 1024 is a reserved port number.

Bytes -------------------------------------------------------------------------------------

At the same time, there is also a basic knowledge of connection-oriented and non-connection-oriented.

There are two types of sockets. One is connection-oriented. A connection is established before communication, and data transmission is sequential, reliable, and non-duplicated, without data boundaries. The main protocol for implementing this connection is the Transmission Control Protocol (TCP). To create a TCP socket, you must specify that the socket type is SOCK_STREAM.

The other is a connectionless socket, that is, data is not connected before transmission, so that the sequence, reliability, and repeatability of data transmission are not guaranteed. The main protocol for this transmission is User Datagram Protocol (UDP ).

Bytes ----------------------------------------------------------------------------------------------

Now, the basics of the network are put down and Python network programming is started.

Python provides a socket module to create and use sockets.

 

Socket () module functions

Socket (socket_family, socket_type, protocol = 0)

This function can be used to create a socket object, respectively writing the socket family name and socket type.

After this socket object is created, all interactions can be performed through the method call of this object.

You can directly check the Python documentation for specific methods. Here is an example to illustrate the process of creating a TCP Server:

From socket import * from time import ctimeHOST = ''# host port = 8002 # PORT number. You can select BUFSIZ = 1024 ADDR = (HOST, PORT) at will) # The host port number forms a socket address tcpSerSock = socket (AF_INET, SOCK_STREAM) # create a socket object, which is a tcp socket tcpSerSock of the AF_INET family. bind (ADDR) # This function is used to bind the address to the socket tcpSerSock. listen (5) # The server starts listening for connections. The parameter indicates that a maximum of several connections can be added at the same time while True: print 'Waiting for connection... 'tcpclisock, addr = tcpSerSock. accept () # used to wait for the arrival of the connection print '... connected from: ', addr while True: data = tcpCliSock. recv (BUFSIZ) # used to receive the data parameters sent from the client to represent the maximum amount of data received at a time. Here 1 k if not data: break tcpCliSock. send ('[% s] % s' % (ctime (), data) # send the timestamp as the content to the client tcpCliSock. close () tcpSerSock. close ()

When running, you can see that the server is running and waiting for a client connection, so now we need to use the client to connect to the server.

Write a simple client program:

From socket import * HOST = 'localhost' # because the server is opened on your computer, the HOST is a local PORT = 8002 # the same connection port bufsiz = 1024 ADDR = (HOST, PORT) tcpCliSock = socket (AF_INET, SOCK_STREAM) # same TCP socket tcpCliSock. connect (ADDR) # connect to the corresponding address and initialize the TCP server connection while True: data = raw_input ('>') if not data: break tcpCliSock. send (data) # transmit data to the server = tcpCliSock. recv (BUFSIZ) # accept server-side data if not data: break print datatcpCliSock. close ()

Now, you can run the client program to verify the program.

 

 

Of course, it is better not to connect locally or connect two computers for the sake of learning pleasure, mainly because the client needs to know the IP address of the server.

IP addresses can be found in network properties,

Then we can use the same program framework to implement communication between the two machines. Finally, we can implement a walkie talkie program, for example:

Of course, it is not that easy to implement a chat tool that both parties can speak freely. A new attempt is required.

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.