Python-based socket programming

Source: Internet
Author: User

One, client/server architecture

That is, the C/s architecture, including:
Hardware/C/S Architecture (printer)
Software c/S Architecture (Web service), b/S architecture is also a C/s architecture.

c/S Architecture in life:
The hotel is the S-end, all diners are C-terminal

The relationship between C/s architecture and socket:
Learning socket is to complete the development of C/s architecture

Ii. OSI Layer Seven

Principle of network communication: http://www.cnblogs.com/linhaifeng/articles/5937962.html
Why learning to socket must first learn the Internet protocol:

First: The goal of this lesson is to teach you how to develop your own C/s architecture software based on socket programming.
Secondly: the software of C/s architecture (software belongs to the application layer) is based on the network communication
Then: The core of the network is a stack of protocols, the Protocol is the standard, you want to develop a network-based communication software, you must follow these standards.
Finally: Let's start with these standards and open our socket programming journey

The TCP/IP protocol family includes transport layer, network layer, and link layer.

Third, Socket Layer

In a illustrated statement:

Iv. what is a 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 design mode, the socket 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 data to meet the specified protocol.

So, we do not need to understand the TCP/UDP protocol, the socket has been packaged for us, we only need to follow the socket rules to program, write the program is naturally follow the TCP/UDP standard.

Someone also said the socket as ip+Port,ip is used to identify the location of a host in the Internet, and port is used to identify an application on this machine, the IP address is configured on the network card, and the port is the application open, The IP-Port binding identifies an application that is unique to the Internet, and the PID of the program is the identity of the different processes or threads on the same machine .
Eye-catching articleFive, the history and classification of the sockets

Sockets originated in the the 1970s UC Berkeley version of Unix, which is what people call BSD Unix. Therefore, sometimes people also refer to sockets as "Berkeley sockets" or "BSD sockets". Initially, sockets are designed to be used for communication between multiple applications on the same host. This is also called interprocess communication, or IPC. There are two types of sockets (or two races), which are file-based and network-based.

Socket family based on file type:

Socket family name: Af_unix
Unix all files, file-based sockets are called by the underlying file system to fetch data, two sockets process running on the same machine, you can access the same file system to complete the communication indirectly

Socket family based on network type:

Socket family name: af_inet
(There are also af_inet6 used for IPv6 and some other address families, but they are either used only on a platform, or have been discarded, or are rarely used, or are not implemented at all, and Af_inet is the most widely used one in all address families, Python supports a variety of address families, but since we only care about network programming, most of the time I use af_inet only)

Six, Socket workflow

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 a 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 once .

Socket () module function usage:

 import   Socketsocket.socket (socket_family, socket_type,protocal  =0) socket_family can be Af_unix or af_inet. Socket_type can be sock_stream or sock_dgram. Protocol is generally not filled, the default value is 0. Get TCP /ip socket tcpsock  = Socket.socket ( Socket.af_inet, Socket. SOCK_STREAM) get UDP /ip socket udpsock  = Socket.socket (socket.af_inet, socket. SOCK_DGRAM) Because there are too many properties in the socket module. We made an exception here with the   " from module Import *  Span style= "COLOR: #800000" "" " statement. Use  from socket import *  "   We took all the attributes in the socket module into our namespace, which greatly shortened our code. For example Tcpsock  = socket (af_inet, sock_stream) 

Service-Side socket functions:

S.bind ()    bind (host, port number) to Socket S.listen ()  Start TCP Listener s.accept ()  passively accept TCP Client connection, (blocked) wait for connection arrival

Client socket functions:

S.connect ()     actively initializes an extended version of the TCP server Connection S.CONNECT_EX ()  connect () function, returning an error code instead of throwing an exception when an error occurs

Socket functions for public use:

S.RECV ()            receives TCP data S.send () sends TCP data (send data is            lost when the amount of data to be sent is greater than the remaining space in the buffer cache) S.sendall ()         sends the full TCP data ( The essence is circular call Send,sendall in the amount of data to be sent is greater than the left buffer space, the data is not lost, loop call send until the end of the Send) S.recvfrom ()        receive UDP data s.sendto ()          Send UDP data S.getpeername () the address of the     remote that is connected to the current socket S.getsockname ()     address of the current socket s.getsockopt ()      Returns the parameter of the specified socket s.setsockopt ()      sets the parameter of the specified socket S.close ()           closes the socket

Lock-oriented socket method:

S.setblocking ()     sets the blocking and non-blocking mode of sockets S.settimeout () to      set the timeout time for blocking socket operations S.gettimeout ()      to get the timeout for blocking socket operations

Functions for file-oriented sockets:

S.fileno () The file descriptor for the socket ()          s.makefile ()        creates a file associated with the socket
Vii. TCP-based sockets

Service side:

Import Socketphone=socket.socket (Socket.af_inet,socket. SOCK_STREAM) #买手机phone. setsockopt (socket. Sol_socket,socket. so_reuseaddr,1) #就是它, add phone.bind (' 127.0.0.1 ', 8080) before bind #绑定手机卡phone. Listen (5) #开机  5print (' starting .... ') While True: #链接循环    conn,addr=phone.accept () #等待电话链接    print (' phone line is ', conn)    print (' client's phone number is ', addr)    While True: #通信循环        try: #应对windows系统            data=conn.recv (1024x768) #收消息  ?            data:break #linux系统            print (' The message sent by the client is ', data ')            Conn.send (Data.upper ())        except Exception: Break    Conn.close () Phone.close ()

Client:

Import Socketphone=socket.socket (Socket.af_inet,socket. Sock_stream) Phone.connect ((' 127.0.0.1 ', 8080)) while True: #通信循环    msg=input (' >>: '). Strip ()    if not msg: Continue    Phone.send (Msg.encode (' Utf-8 '))    print (' has send===========> ')    data=phone.recv (1024)    print (' has recv===========> ')    print (data) phone.close ()

Note: You may experience when restarting the server:

Since the service side still exists four times the time_wait state of the wave in the Occupy address (please delve into the 1.tcp three times handshake, four wave 2.syn flood Attack 3.) high server concurrency scenarios with a large number of time_wait state optimization methods

Workaround:

# Add a socket configuration to reuse IP and ports phone=socket (af_inet,sock_stream) phone.setsockopt (sol_socket,so_reuseaddr,# is it, Add phone.bind ('127.0.0.1', 8080) before bind
leaning on the day sword
/etc/= 1= 1= 1=/sbin/sysctl-= 1= 1 means turn on reuse. Allow time-= 1 To turnon fast recycling of time-WAIT sockets in TCP connections, which by default is 0, indicates off. Net.ipv4.tcp_fin_timeout Modifying the default timeout time method for the system two
Dragon Slayer Knife

Python-based socket 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.