Python\socket Programming 2

Source: Internet
Author: User

1 history and development of 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)

The network type is divided into TCP and UDP Two kinds

2 socket Workflow (TCP)

TCP Transmission Control Protocol

TCP is a reliable transmission that sends packets after the other party returns the message and deletes the package

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.

Simulation Exercise: #服务器phone =socket.socket (Socket.af_inet,socket. SOCK_STREAM) #SOCK_STREAM是TCP协议phone. Bind (("127.0.0.1", 8080)) #绑定手机卡  bind (host, port number) to socket Phone.listen (5) # Listen function: Establish a connection  to   start TCP listening while True: #连接循环    conn,addr=phone.accept () #等待电话连接  passively accept a link    to a TCP client Print ("Phone line is", conn)    print ("Client's phone number is", addr)    # CONN.RECV (1024) Receive message while    True:        try:            data= CONN.RECV (1024x768) #接收TCP数据, 1024 is the maximum limit or 8192            print ("message sent by the client is", data)            Conn.send (Data.upper ()) #发送TCP数据        except Exception:            break    Conn.close () phone.close () #客户端import Socketphone=socket.socket (socket.af_ Inet,socket. SOCK_STREAM) #买手机phone. Connect (("127.0.0.1", 8080) #主动初始化TCP服务器连接while True: #通信循环    msg=input (">>")    if not msg:continue# input information cannot be empty    phone.send (Msg.encode ("UTF8")) #发送TCP数据    data=phone.recv (1024x768)    Print (data) phone.close () #关闭套接字

  

The service-side socket function S.bind ()    binds (host, port number) to Socket S.listen ()   starts TCP listener s.accept ()  passively accepts the TCP client link, Incoming (blocked) waiting for a connection the client socket function S.connect ()  actively initializes an extended version of the TCP server Connection S.CONNECT_EX ()   connect () function, returning an error code when an error occurs, Instead of throwing an exception to the public-use socket function 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 cache) S.sendall ()   Send complete TCP data (essentially a cyclic call to Send,sendall when the amount of data to be sent is greater than the remaining space in the cache, the data is not lost, the loop calls 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 for the lock socket Method s.setblocking ()     Sets the blocking and non-blocking mode for sockets S.settimeout () to      set the timeout time for a blocked socket operation S.gettimeout ()      Gets the timeout time for a blocked socket operation the function of a socket for a file S.fileno ()          The socket's file descriptor S.makefile ()        creates a file associated with the socket

Problems that you may encounter

This is due to the TIME_WAIT state of the server still waving four times in the occupied address

Solution: Add a socket configuration, reuse IP and Port phone=socket (af_inet,sock_stream) phone.setsockopt (sol_socket,so_reuseaddr,1) #就是它, Add Phone.bind (' 127.0.0.1 ', 8080) before bind to find that the system has a large number of time_wait state connections, by tuning the Linux kernel parameters to resolve, vi/etc/ sysctl.conf Edit the file, add the following: Net.ipv4.tcp_syncookies = 1net.ipv4.tcp_tw_reuse = 1net.ipv4.tcp_tw_recycle = 1net.ipv4.tcp_ Fin_timeout = 30 Then execute/sbin/sysctl-p to let the parameters take effect. Net.ipv4.tcp_syncookies = 1 means that Syn Cookies are turned on. When a SYN wait queue overflow occurs, cookies are enabled to protect against a small number of SYN attacks, the default is 0, which means close; Net.ipv4.tcp_tw_reuse = 1 means turn on reuse. Allow time-wait sockets to be reused for new TCP connections, which defaults to 0, which means shutdown, net.ipv4.tcp_tw_recycle = 1 for fast recycling of time-wait sockets on TCP connections, and 0 for shutdown by default. Net.ipv4.tcp_fin_timeout Modify the default timeout time for the system

  

Python\socket Programming 2

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.