Python Learning--socket sockets (TCP connection)

Source: Internet
Author: User

Socket Basics

c/S architecture, that is, client/server architecture, B/S Architecture (Browser/server), also belongs to C/s architecture

Socket INTRODUCTION

Socket socket is to complete the development of C/s architecture software. The socket relies on the network, so the network foundation cannot be forgotten.

In Python, the socket layer is located in the middle layer of the transport and application tiers of the TCP/IP stack and is a software abstraction layer that provides an up-down interface. The socket encapsulates the TCP and UDP protocols, so programs written in the socket syntax follow the TCP and UDP protocols

NOTE: socket = IP + port,ip is used to identify the location of the host in the network, port is used to identify the host's application, so IP + port can identify the only application in the Internet, so that the socket is actually a combination of IP and port

Socket category

Network programming only need to pay attention to af_inet, this is the most widely used, if the IPv6 platform needs to use AF_INET6.

Other: Af_unix, used for communication between UNIX file systems, and many other platforms.

Socket Communication principle

For the SOCKETTCP communication process :

1. The server initializes the socket, then binds to the port (BIND), listens to the port (listen), and calls the accept blocking wait

2. The client connection initializes a socket and then connects to the server (connect), and if the server side is properly accessed, the server end is blocked and the connection is successful, then the connection between the client and the server is established.

3. The client sends a data request, the server receives the request and processes the request, and the server sends the response data to the client, the client reads the data, and loops.

4. The last client or server closes the connection and ends the interaction.

Socket module

Example: one-time socket communication based on a local loopback address

Service side:

#导入socket模块import socket# Create a socket, similar to buying a phone skt=socket.socket (socket.af_inet,socket. SOCK_STREAM) #绑定端口和ip, must be a tuple type, similar to the phone card #, if the tuple is (", 9000) represents all of the local network card, equivalent to 0.0.0.0skt.bind ((' 127.0.0.1 ', 9000)) #侦听访问端口, Similar to phone standby # If there is a value in parentheses, the optimization of the TCP connection is Skt.listen () #此处循环表示服务器持续提供服务while True:    #conn表示接受的数据流, addr represents the address of the client    conn,addr =skt.accept ()    #接受客户端发送消息并打印    msg=conn.recv    print (Msg.decode (' Utf-8 '))    print (Msg,type (msg) )    #为客户端返回消息, indicating acceptance of success    Conn.send (Msg.upper ())    #关闭本次通信    conn.close ()    #关闭链接    skt.close ()                     

Client

#导入socket模块import  socket# Create Socketskt = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #与服务端建立链接skt. Connect ((' 127.0.0.1 ', 9000)) #发送消息msg = B ' Hello ' Skt.send (msg) #接受服务端返回值并打印res = SKT.RECV (100 ) Print (Res.decode (' Utf-8 ')) #关闭会话链接skt. Close ()

#相关值说明

1 Socket.socket (socket_family,socket_type,protocal=0) 2 socket_family can be Af_unix or Af_inet3 Socket_type can be SOCK_ STREAM (reliable connection-oriented data transfer, TCP protocol) or SOCK_DGRAM (non-connected unreliable data transfer, UDP) 4 protocol generally not filled, the default value is 0

#相关方法说明

1 Service End Socket function 2 S.bind ()    binding (host, port number) to Socket 3 S.listen ()  start TCP Listener 4 s.accept ()  passively accept TCP Client connection, (blocked) wait for connection arrival 5  6 Client socket Function 7 S.connect ()     actively initializes an extended version of the TCP server Connection 8 S.CONNECT_EX ()  connect () function, returns an error code when an error occurs, instead of throwing an exception 9 10 socket function for public use 11 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), and the         full TCP data is sent by S.sendall () ( 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 S.recvfrom ()        receive UDP data () s.sendto ()          Send UDP data s.getpeername ()     Connect to the far end of the current socket S.getsockname () address of the     current socket s.getsockopt ()      returns the parameter 19 of the specified socket S.setsockopt ()      sets the parameter of the specified socket S.close ()           close socket 21 22 lock-oriented socket Method s.setblocking ()     sets the blocking and non-blocking mode for sockets 24 S.settimeout ()      set timeout for blocking socket operation S.gettimeout ()      get blocked socket operation Timeout 26 27 function for file-oriented sockets S.fileno ()          Socket file Descriptor S.makefile ()        creates a file associated with the socket

#常见错误处理

 

Because the service side still exists four times the time_wait state of the wave in the Occupy address (if not understand, please delve into 1.tcp three times handshake, four waves wave 2.syn flood attack 3.) high-level Time_wait state optimization method in case of higher server concurrency

The most straightforward workaround, change the port number

More Solutions:

Window Resolution method

1 #加入一条socket配置, Reuse IP and Port 2 phone=socket (Af_inet,sock_stream) 3 phone.setsockopt (sol_socket,so_reuseaddr,1) #就是它, Add 4 phone.bind (' 127.0.0.1 ', 9000) before bind

Linux Solutions

1 Discovery System has a large number of time_wait state connections, by adjusting the Linux kernel parameters resolved, 2 vi/etc/sysctl.conf 3  4 Edit the file, add the following: 5 net.ipv4.tcp_syncookies = 1 6 net.i Pv4.tcp_tw_reuse = 1 7 net.ipv4.tcp_tw_recycle = 1 8 net.ipv4.tcp_fin_timeout = 9 10  then execute/sbin/sysctl-p to let the parameters take effect.  net.ipv4.tcp_syncookies = 1 indicates 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, and the default is 0, which means close; Net.ipv4.tcp_tw_reuse = 1 means turn on reuse. Allows the time-wait sockets to be reused for new TCP connections, which defaults to 0, which means close, and net.ipv4.tcp_tw_recycle = 1 for fast recycling of time-wait sockets on TCP connections, which defaults to 0. Indicates close. Net.ipv4.tcp_fin_timeout Modify the default timeout time for the system

Python Learning--socket sockets (TCP connection)

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.