Article directory
The underlying network interface socket is built into the python standard library, and the following codes are all defaultfrom socket import *
Preliminary Understanding
socket
Translated 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 send
the content to be sent is binary code, so it is encoded and decoded by encode
sum . decode
Finally exit
exit 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.socket
an object is created with socket
the complete constructor of
socket.socket(family=AF_INET, type=SOCK_STREAM,proto=0,fileno=None)
Among them, family
the 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 .
type
For 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_CAN
family is , the protocol should be CAN_RAW
, CAN_BCM
, CAN_ISOTP
or CAN_J1939
.
fileno represents a created socket
file.
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
, accept
these three methods are proprietary methods of the server , and their functions are
bind(address)
: bind it to an address, where the addressaddress
is generally a tuple, including IP and port numberlisten(N)
: Start a server to accept connections,N
the maximum number of connections, not less than 0.accept()
: accepts a connection, no parameters, the return value is a(conn, address)
tuple, whichconn
is a newsocket
object for sending and receiving data.
Accordingly, the client also has two dedicated methods
connect(address)
: Connect to an address.connect_ex(address)
:connect
In 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 send
and receiving recv
.
Among them, the functions related to sending are
send(bytes)
: Among thembytes
is the sent byte, and returns the sent byte (sometimes it may not be sent completely).sendall(bytes)
:send
Compared with, will continue to sendbytes
until all data has been sent or an error is reported.sendfile(file,offset=0,count=None)
: Send a file under Unix, and thesend
same 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 bufsize
represent 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) |
flag is false non-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 socketdetach()
closes the socket object, but does not close the file descriptor
shutdown(how)
how
A connection to a socket can be partially closed, where
SHUT_RD
: Subsequent reception is no longer allowedSHUT_WR
: Subsequent sending is no longer allowedSHUT_RDWR
: Subsequent sending and receiving are not allowed