Python Learning 1:socket Module (TCP/IP network programming)

Source: Internet
Author: User

This article only cares about Python's network programming and focuses on TCP/IP units.

First, a simple understanding of the following:

1, what is TCP/IP,UDP?

TCP/IP (transmission Control protocol/internet Protocol) is a protocol/inter-network protocol, an industry-standard set of protocols designed for wide area networks (WANs).
UDP (user Data Protocol, Subscriber Datagram Protocol) is the protocol that corresponds to TCP. It is a part of the TCP/IP protocol family.
Here is a diagram showing the relationship of these protocols.


The TCP/IP protocol family includes transport layer (transport layer), network layer, (data) Link layer. Now you know the relationship between TCP/IP and UDP.

2 . Where is the Socket?
in , we don't see the socket shadow, so where is it? Or use a diagram to speak, at a glance.

The original socket is here.


3 . What is Socket?
A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In the design mode, thesocket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize the data, To conform to the specified protocol.

4, how to use the socket?

predecessors have done a lot of things to us, the communication between the network is a lot simpler, but after all, there is still a lot of work to do. Previously heard socket programming, think it is more advanced programming knowledge, but as long as understand how the socket programming principle, the mysterious veil also opened.
A scene in the life. You have to call a friend, dial first, a friend hears a phone call, and then you and your friend establish a connection, you can talk. When the communication is over, hang up the phone and end the conversation. the scene in life explains this work principle, perhaps the TCP/IP protocol family is born in the life, this is not necessarily.

Start with the server side. The server-side initializes the Socket, then binds to the port (BIND), listens to the port (listen), calls the accept block, waits for the client to connect. At this point if a client initializes a Socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at the end.

Second, socket module function

Because there are too many properties in the socket module, you can use the import socket directly, which greatly reduces the code.

1. Socket (Family,type)

Creates a socket.

Sockets are computer network data structures. A networked application must create a socket before any communication can begin. Can be compared to the telephone socket, without it there is no way to communicate.

To create a TCP/IP socket:

1 tcpsock = socket (af_inet, SOCK_STREAM)

To create a UDP/IP socket:

1 udpsock = socket (af_inet, SOCK_DGRAM)

AF: Abbreviation for address family

Sock_stream: For connection sockets, be sure to have a resume connection before communication (like calling a friend). The connection-oriented approach provides sequential, reliable, and repeatable data transfers, and does not add to the boundary of the database. When the message is sent, the information can be split into multiple parts, no points will arrive at the correct destination, and then re-assembled in order to pass the waiting application.

Sock_dgram: There is no connection socket, that is, you can communicate without establishing a connection. At this point, however, data arrival is not guaranteed by order, reliability, and repeatability, and the datagram preserves data boundaries. The data is sent throughout. Using datagrams to transfer data is like a courier package, not necessarily in the order of delivery, and it may not be possible to reach it at all.

2. Socket object (built-in) method

Function Describe
Server-side socket functions
S.bind ()

Bind address (host name, port number) to socket

The legal port number range is 0~65535. Where less than 1024 is the system reserved port and the rest is available

S.listen () Start TCP snooping. parameter indicates the maximum number of connections allowed at the same time, and the subsequent connection will be rejected
S.accept () (blocked) accepts a connection and returns (Conn,address), Conn is a new socket object that can be used to send and receive data over a connection, and address is the socket addressing of another connection end
Client socket functions
S.connect () Connect to the remote socket at address. Socket.error occurs when there is an error
S.CONNECT_EX () Extended version of Connect (), which returns an error code instead of throwing an exception when an error occurs. Successful return 0
Socket functions for public use
S.RECV (bufsize [, flags]) Receives TCP data. BUFSIZE Specifies the maximum amount of data to receive. Flags provides additional information about the message, usually ignoring
S.send () Sending TCP data
S.sendall () Complete sending of TCP data
S.recvfrom (bufsize [, flags]) Receive UDP data. Return (data,address), data is the receiving string, address is the socket that sends the data
S.sendto (string [, Flags],address) Send UDP data. Address form is a tuple that specifies a remote address
S.fileno () Returns the file descriptor of a socket
S.makefile (Mode[,bufsize]) Creates a file object associated with the socket. Mode in ' R ' means read, ' W ' means write, ' a ' means add, ' + ' means read-write, ' B ' means binary access.

3. Abnormal

Error: The exception represents a socket or address-related fault. It returns a (ERRNO,MESG) pair and the error returned by the underlying system call. Inherit from IOError.

Herror: Represents an address-related error. Returns a Ganso (HERRNO,HMESG) that contains an error message for the error number. Inherit from error.

4. Create a TCP connection instance code

Client

1 ImportSocket2 3HOST ='192.168.1.100'                          #Server IP4PORT = 12345#Port number5Bufsiz = 10246ADDR =(Host,port)7 8Tcpclisock = socket (af_inet,sock_stream)#Create a TCP/IP socket9Tcpclisock.connect (ADDR)#try to connect to the serverTen  One  whileTrue: Adata = input ('>') -     if  notData: -          Break theTcpclisock.send (data)#Sending TCP Data -data = TCPCLISOCK.RECV (Bufsiz)#receiving TCP Data -     if  notData: -          Break +     Print(data) -  +Tcpclisock.close

Server

1 ImportSocket2 Import Time3 4HOST ='192.168.1.100'5PORT = 123456BUFSIZE = 10247ADDR =(Host,port)8 9Tcpsersock =socket (af_inet,sock_stream)Ten Tcpsersock.bind (ADDR) OneTcpsersock.linsten (5) A  -  whileTrue: -     Print('waiting for connection ...') theTCPCLISOCK,ADDR =tcpsersock.accept () -     Print('... connected from:', addr) -      -      whileTrue: +data =tcpclisock.recv (BUFSIZE) -         if  notData: +              Break ATcpsersock.send (('[%s]%s'%(CTime (), data))) at  - tcpclisock.close () -Tcpsersock.close ()

Code implementation:

When there is a connection, enter the conversation loop and wait for the client to send the data. If the message is empty, it indicates that the client has exited and waits for the next client connection. After the client message is received, a timestamp is called before the message and then returned.

To open the server first, then open the client.

5. Create UDP Connection Instance code

Client

1 ImportSocket2  3HOST ='192.168.1.100'                          #Server IP4PORT = 12345#Port number5Bufsiz = 10246ADDR =(Host,port)7Udpclisock =socket (Af_inet,sock_dgram)8 9  whileTrue:Tendata = input ('>') One     if  notData: A          Break -Udpclisock.sendto (DATA,ADDR)#Send UDP data -DATA,ADDR = Udpclisock.recvfrom (bufsiz)#Receive UDP data the     if  notData: -          Break -     Print(data) - udpclisock.close () +Udpclisock.close

Server

1 ImportSocket2 Import Time3  4HOST ='192.168.1.100'                          #Server IP5PORT = 12345#Port number6Bufsiz = 10247ADDR =(Host,port)8 9Udpsersock =socket (Af_inet,sock_dgram)Ten Udpsersock.bind (ADDR) One  A  whileTrue: -     Print('waiting for message ...') -DATA,ADDR =Udpsersock.recvfrom (Bufsiz) theUdpsersock.sendto ('[%s]%s'%(CTime (, data), addr)) -     Print('... received from and returned to:', addr) -Udpclisock.close

An important difference between UDP and TCP servers is that because the datagram socket is not connected, the client connection cannot be forwarded to another socket for subsequent communication. These server knowledge accepts the message and, if necessary, returns a result to the client.

The server outputs the client information because the server may get and reply to multiple client messages, at which point the output will be able to understand what the department is from. For a TCP server, because the client creates a connection, we naturally know where the message came from.

Python Learning 1:socket Module (TCP/IP network programming)

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.