Preliminary python socket (socket) communication

The underlying network interface socket is built into the python standard library, and the following codes are all defaultfrom socket import *

Preliminary Understanding

socketTranslated to socket, although some people criticize it, I think it is quite appropriate. Its function is to provide low-level network services, the most commonly used is to transmit data based on IP.

The so-called transmission, there must be two "ends", first of all to be a server

import socket
s = socket.socket()
host = socket.gethostname() #本机地址   
port = 12345                #端口
s.bind((host,port))         #绑定端口
s.listen(3)     #开始监听,最多支持三个链接
while True:
    c, addr = s.accept()    #等待连接
    print("Linked @ Addr",addr)
    break

#下面为发送命令
while True:
    data = input("input data:")
    c.send(data.encode("utf8"))
    if data=="exit":
        c.close()
        break

It should be noted that sendthe content to be sent is binary code, so it is encoded and decoded by encodesum . decodeFinally exitexit if entered.

then write a client

import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host,port))
while True:
    data = s.recv(1024).decode("utf8")
    if data!=b'':
        print("receive data:", data)
    # 当接收到exit时关闭端口,退出循环
    if data[:4]=="exit":
        s.close()
        break

After running, the input and output of the server and the client are respectively

#服务端
Linked @ Addr ('192.168.1.113', 9953)
input data:hello world
11
input data:who are you
11
input data:can u speak chinese?
20
input data:exit
4

#客户端
receive data: hello world
receive data: who are you
receive data: can u speak chinese?
receive data: exit

socket object

In the above example, socket.socketan object is created with socketthe complete constructor of

socket.socket(family=AF_INET, type=SOCK_STREAM,proto=0,fileno=None)

Among them, familythe address family representing the socket mainly includes three categories

address family AF_INET AF_INET6 AF_UNIX
Protocol source IPv4 IPv6 UNIX

|When creating a serial port, multiple address families can be selected at the same time by OR operation .

typeFor the socket type, there are two commonly used

  • SOCK_STREAM, for streaming sockets, is characterized by the same order of transmission and reception, which is safe.
  • SOCK_DGRAM, a datagram format socket, characterized by fast, unordered, and possible loss

proto is the protocol number, generally 0. When the protocol AF_CANfamily is , the protocol should be CAN_RAW, CAN_BCM, CAN_ISOTPor CAN_J1939.

fileno represents a created socketfile.

Although the constructor does not declare the parameters of the client and the server , the members that can be called by the two should not be exactly the same in terms of function.

Among them, bind, listen, acceptthese three methods are proprietary methods of the server , and their functions are

  • bind(address): bind it to an address, where the address addressis generally a tuple, including IP and port number
  • listen(N): Start a server to accept connections, Nthe maximum number of connections, not less than 0.
  • accept(): accepts a connection, no parameters, the return value is a (conn, address)tuple, which connis a new socketobject for sending and receiving data.

Accordingly, the client also has two dedicated methods

  • connect(address): Connect to an address.
  • connect_ex(address): connectIn contrast, when an error occurs, return an error code without reporting an error.

Next are the methods that can be used by both the client and the server, the most critical of which are sending sendand receiving recv.

Among them, the functions related to sending are

  • send(bytes): Among them bytesis the sent byte, and returns the sent byte (sometimes it may not be sent completely).
  • sendall(bytes): sendCompared with, will continue to send bytesuntil all data has been sent or an error is reported.
  • sendfile(file,offset=0,count=None): Send a file under Unix, and the sendsame under Windows, it is equivalent to not available.
  • sendto(bytes,addresss): Specify the address to send data.

There are two sets of receive-related functions available in Windows, which bufsizerepresent the maximum number of bytes of received data.

return data Return data + receiver address
don't write to buffer recv(bufsize) recvfrom(bufsize)
write bufferbuf recv_into(buf,bufsize) recvfrom_into(buf,bufsize)

get-set is a function name that appears in many modules. The former represents getting certain parameters, and the latter represents setting certain parameters. Generally, the input of the latter is the output of the former.

get set
get_inheritable() set_inheritable(i) socket file descriptor
getblocking() setblocking(flag) flagis falsenon-blocking, otherwise blocking
getpeername() Get the remote address the socket is connected to
getsockname() Get socket local address
gettimeout() settimeout(value) timeout seconds

There are several ways to abort or close a socket

  • close()close the file descriptor of the socket
  • detach()closes the socket object, but does not close the file descriptor

shutdown(how)howA connection to a socket can be partially closed, where

  • SHUT_RD: Subsequent reception is no longer allowed
  • SHUT_WR: Subsequent sending is no longer allowed
  • SHUT_RDWR: Subsequent sending and receiving are not allowed

Guess you like

Origin blog.csdn.net/m0_37816922/article/details/122419972