python --socket (socket/socket)

What is a socket?

**
is a method of inter-process communication. One of its main differences from other inter-process communications is that it can realize process communication between different hosts. Our network Most of the various services on the Internet are based on sockets to complete communication. For example, we browse the web, chat on QQ, and send and receive emails; **
Socket is the communication between the application layer and the TCP/IP protocol family. An intermediate software abstraction layer, which is a set of interfaces. In the design mode, Socket is actually a facade mode, which hides the complex TCP/IP protocol family behind the Socket interface. For users, a set of simple interfaces is everything.

1. Create socket

This can be done by using the function socket of the socket module in python,
Description: The function socket.socket creates a socket. This function has two parameters:< a i=2> import socket socket.socket (AddressFamily represents whether to use IPv4 or v6, Type represents whether to use tcp or udp)

2. Create udp connection

#创建udp连接
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)


#不用的时候关闭连接
s.close()
#udp发    没有固定端口绑定
import socket
def main():
    #1、创建udp连接
    udp_s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    #可以用套接字收发数据了
    #2、准备接收方的地址
    #‘192.168.1.1’表示目的ip地址
    #8080表示目的端口
    dest_addr=('192.168.1.1',8080)#注意是元组,ip是字符串,端口是数字
    #3、从键盘获取数据
    send_data=input("请输入要发送的数据:")
    #4、发送数据到指定的电脑上的指定程序中
    udp_s.sendto(send_data.encode('utf-8',dest_addr))
    #或
    udp_s.sendto(b"hello world",('192.168.1.1',8080))
    #不用的时候关闭连接
    udp_s.close()
    print("run")
if __name__=="__main__":
    main()

Sockets originated from Unix, and one of the basic philosophies of Unix/Linux is that "everything is a file", and can be operated using the "open -> read and write write/read -> close" mode. Socket is an implementation of this mode. A socket is a special file, and some socket functions are operations on it (read/write IO, open, close)

You want to send a message to another computer. You know its IP address. QQ, Thunder, word, browser and other programs are running on his machine at the same time. If you want to send a message to his QQ, then think about it. You are now His machine can only be found through IP, but what if this machine knows to send messages to the qq program? The answer is through port. There can be 0-65535 ports on a machine. If your program wants to send and receive data from the network, it must bind a port. In this way, all data sent to this port remotely will be transferred to this program. La

#udp接收    绑定固定端口
import socket
from socket import *
def main():
    #1、创建udp套接字
    udp_s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    #2、绑定本地相关信息,如果一个网络程序不绑定,则系统会随机分配
    locale_addr=('',7788)#ip地址和端口号,ip一般不用写,表示本机的任何一个ip(注意是空不是空格)
    udp_s.bind(locale_addr)#必须只能绑定自己的信息,其他的不行
    #3、等待接收对方发送的数据
    recv_data=udp_s.recvfrom(1024)#1024表示本次接收的最大字节数
    #4、显示接收到的数据
    print(recv_data[0].decode('gbk'))#encode编码utf-8,decode解码gbk

    #5、关闭套接字
    udp_s.close()
if __name__=="__main__":
    main()

family(socket family)

socket.AF_UNIX: used for local inter-process communication. In order to ensure program security, two independent programs (processes) cannot access each other's memory. However, in order to achieve inter-process communication, you can use Create a local socket to complete
socket.AF_INET: (There is also AF_INET6 used for ipv6, and there are some other address families, but they are either only used on a certain platform, or It has been abandoned, or is rarely used, or has not been implemented at all. Among all address families, AF_INET is the most widely used one. Python supports many address families, but since we only care about network programming, most of the time We only use AF_INET)
socket type
socket.SOCK_STREAM #for tcp
socket.SOCK_DGRAM #for udp proto=0 Please ignore , special purpose (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.) socket.SOCK_SEQPACKET #Abandoned socket.SOCK_RDM # is a reliable form of UDP, which guarantees the delivery of datagrams but does not guarantee the order. SOCK_RAM is used to provide low-level access to the original protocol and is used when certain special operations need to be performed, such as sending ICMP messages. SOCK_RAM is usually restricted to programs run by power users or administrators.
socket.SOCK_RAW #Original socket. Ordinary sockets cannot process network messages such as ICMP and IGMP, but SOCK_RAW can. Secondly, SOCK_RAW can also process special IPv4 messages. In addition, using Raw socket, IP header can be constructed by the user via the IP_HDRINCL socket option.



fileno=None please ignore, special purpose

Server-side socket function
s.bind() binds (host, port number) to the socket
s.listen( ) Start TCP monitoring
s.accept() passively accepts TCP client connections, (blocking) waiting for the arrival of the connection client socket function (2 minutes)
s.connect() actively initializes the TCP server connection
s.connect_ex() An extended version of the connect() function that returns an error code when an error occurs instead of throwing an exception. Public-purpose socket Word function (3-5 minutes)
s.recv() Receive data
s.send() Send data (send is used when the amount of data to be sent is greater than the own end) When there is remaining space in the buffer, the data will be lost and will not be sent completely. This can be explained later through examples)
s.sendall() sends complete TCP data (essentially calling send in a loop, sendall is waiting to be sent) When the amount of data is greater than the remaining space in the end buffer, the data is not lost, and send is called in a loop until it is sent out)
s.recvfrom() Receive data from the socket. The return value is a pair (bytes , address)
s.getpeername() Connect to the remote address of the current socket
s.close() Close the socket
socket.setblocking(flag) #True or False, set the socket to non-blocking mode, which will be used when talking about asynchronous io in the future
socket.getaddrinfo(host, port, family=0 , type=0, proto=0, flags=0) Returns the address information of the remote host, example socket.getaddrinfo('http://luffycity.com',80)
socket.getfqdn( ) Get the host name of this machine
socket.gethostbyname() resolves the ip address through the domain name

Guess you like

Origin blog.csdn.net/m0_57297999/article/details/129639910