2015/12/14 Python network programming, TCP/IP client and server exploration

Source: Internet
Author: User

Has not been very clear about the server definition, for what is the server/client architecture is also only a vague feeling. Recently started learning to understand some of the relationship between server and client.

The so-called server, is the provision of services, it is a hardware or software, to one or more clients to provide the required services. It exists to wait for the customer's request, then to serve the customer, and then wait for the request.

The client, on the other, comes up with a server, presents its own request, and waits for feedback.

For example, a printer is an example of a server, connected to the computer is the client, connected to the printer through the network, to give IT service requirements (printing) and transfer data (transfer content), and then the printer to work, or return the cause of the service failure (such as the lack of paper or no ink) the printer is the server side, It is a waiting request, it is working, the computer is the client side, it is not a work.

The printer is a hardware server, there are some software servers, such as Web servers, database servers and so on.

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

So how do they connect over the Internet? How is network programming between client/server done?

First, we want to create a power outage for a communication that allows the server to "listen" for requests, like a company's phone, where a customer issues a request to the company over a telephone device.

Of course, a server after the phone has to have their own phone to potential customers, in order to get a response, that is, the site must be sent to customers to be useful.

For the client, the same is the creation of a communication endpoint, and then establish a connection to the server, the customer can make the request.

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

For communication endpoints, introduce a concept called sockets.

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

Just like we apply an integer floating-point Boolean, the socket is also a data structure that we use to access the network.

The sockets originated in the 70 's, on UNIX in the University of California, Berkeley version, and was originally designed to communicate on multiple applications on the same machine, i.e. interprocess communication, in two types, one based on file system and one based on network.

It makes sense to have a file system that is used for different process communication because the file system is accessible to different processes. Network-based sockets are necessary for different computers.

I will consider only the network-based sockets, there are two kinds of address family, one is af_inet, the other is Af_netlink. Most of the time, we're talking about af_inet sockets with links.

The address of a socket is made up of two parts, one is a host and the other is a port.

Similar to the meaning of the area code and phone number of the telephone network. The host determines the machine you are accessing, which is an IP address, which is the port number used by the server software you are accessing. A machine can have a number of programs are using the port, the legitimate port number range is 0~65535. A port number less than 1024 is the port number that the system retains.

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

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

There are two types of sockets, one for connection-oriented, one for connecting before communication, and then for sequential, reliable, no-duplication data transfer, and no boundary. The primary protocol that implements this connection is Transmission Control Protocol (TCP), which creates a TCP socket to specify that the socket type is sock_stream.

The other is a non-connected socket, that is, the transmission of data before the connection, so that the sequence of data transmission, reliability, non-repeatability is not guaranteed. The primary protocol for this transmission is User Datagram Protocol (UDP).

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

At this point, the foundation of the network to put aside, began to talk about Python network programming.

Python provides a socket module to create and use sockets.

Socket () module function

Sockets (Socket_family, Socket_type, protocol=0)

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

Once the socket object has been created, all interactions can be made through the object's method invocation.

The specific method can be directly to the Python document, I here to illustrate the process of creating a TCP server:

 fromSocketImport* fromTimeImportCtimehost="# HostPORT= 8002 # port number, can be arbitrarily selectedBufsiz= 1024ADDR=(HOST, PORT) #主机端口号组成一个套接字地址tcpSerSock=socket (af_inet, sock_stream) #创建一个套接字对象, is the Af_inet family of TCP sockets Tcpsersock.bind (ADDR) # This function is used to bind the address to the socket Tcpsersock.listen (5# The server starts listening for connections, and the parameters represent a maximum number of connections allowed at the same time whileTrue:Print 'waiting for connection ...'Tcpclisock, addr=tcpsersock.accept () #用于等待连接的到来Print '... connected from:', addr whileTrue:data=tcpclisock.recv (bufsiz) #用于接收从客户端发来的数据 parameter represents the maximum amount of data accepted at one time, here is 1kif  notData: BreakTcpclisock.send ('[%s]%s'%(CTime (), data) # Send timestamp as content to client Tcpclisock.close () Tcpsersock.close ()

At runtime, you can see that the server is running and waiting for a client to connect, so at this point we need to use the client to connect to the server.

To write a simple client-side program:

 fromSocketImport*HOST='localhost' #由于服务器开设在自己电脑上, so the host is localPORT= 8002 #同一个连接端口Bufsiz= 1024ADDR=(HOST, PORT) Tcpclisock=socket (af_inet, Sock_stream) #同样的TCP套接字tcpCliSock. Connect (ADDR) # Connect the appropriate address to initialize the connection to the TCP server whileTrue:data= Raw_input ('>')    if  notData: Breaktcpclisock.send (data) # to the server=Tcpclisock.recv (BUFSIZ) # Accept server-side dataif  notData: Break    Printdatatcpclisock.close ()

At this point, you run the client's program, you can verify the program.

Of course, in order to learn the fun, it is best not to connect locally, or take two computers to connect better, mainly the client to know the server-side IP address.

The IP address can be found in the network properties.

Then with the same program framework can be achieved between the two machine communication, and finally can be done as a walkie-talkie program:

Of course, it is not so easy to be a chat tool where both sides can speak freely. There is a need for new attempts.

2015/12/14 Python network programming, TCP/IP client and server exploration

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.