Python full stack road series socket

A socket is a network connection endpoint. For example, when your web browser requests the website of www.baidu.com, your web browser creates a socket and instructs it to connect to the web server host of www.baidu, com, and the web server also sends a socket to the incoming request. monitor on. Both ends use their own sockets to send and receive information.

When in use, each socket is bound to a specific IP address and port. The IP address is a sequence of 4 numbers, all of which are values ​​in the range 0~255; the value range of the port value is 0~65535. Port numbers less than 1024 are reserved for well-known network services; the maximum reserved number is stored in the IPPORT_RESERVED variable of the socket module.

Not all IP addresses are visible to the rest of the world. In fact, some are reserved for non-public addresses (like 192.168.yz or 10.xyz). The address 127.0.0.1 is the local address; it always points to the current computer. Programs can use this address to connect to other programs running on the same computer.

IP addresses are hard to remember, you can pay a little money to register a hostname or domain name for a specific IP address. Domain Name Servers (DNS) handle the mapping of names to IP addresses. Every computer can have a hostname, even if it is not officially registered.

Python provides two basic socket modules.

  1. The first is Socket, which provides the standard BSD Sockets API.
  2. The second is SocketServer, which provides server-centric classes that simplify the development of web servers.

Socket object

sk = socket.socket (socket.AF_INET, socket.SOCK_STREAM, 0)

Parameter one: address cluster

parameter describe
socket.AF_INET IPv4 (default)
socket.AF_INET6 IPv6
ocket.AF_UNIX Can only be used for interprocess communication on a single Unix system

Parameter two: type

parameter describe
socket.SOCK_STREAM streaming socket , for TCP (default)
socket.SOCK_DGRAM datagram socket , for UDP
socket.SOCK_RAW Raw sockets, ordinary sockets cannot handle ICMP, IGMP and other network packets, but SOCK_RAW can; secondly, SOCK_RAW can also handle special IPv4 packets; in addition, using raw sockets, IP_HDRINCL sockets can be used Option to construct the IP header by the user.
socket.SOCK_RDM is a reliable form of UDP, i.e. datagrams are guaranteed to be delivered but not in 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 advanced users or administrators.
socket.SOCK_SEQPACKET Reliable continuous packet service

Parameter 3: Protocol

parameter describe
0 (default) The protocol related to a specific address family. If it is 0, the system will automatically select a suitable protocol according to the address format and socket type.

Socket class method

method describe
s.bind(address) Bind the socket to the address. The format of the address address depends on the address family. Under AF_INET, the address is represented as a tuple (host, port).
sk.listen(backlog) Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before rejecting the connection.
sk.setblocking(bool) Whether to block (default True), if set to False, then an error will be reported once there is no data during accept and recv.
sk.accept() Accept the connection and return (conn, address), where conn is the new socket object that can be used to receive and send data. address is the address of the connecting client.
sk.connect(address) Connect to the socket at address. Generally, the format of address is a tuple (hostname, port). If the connection fails, socket.error is returned.
sk.connect_ex(address) Same as above, but there will be a return value, 0 is returned when the connection is successful, and the code is returned when the connection fails, for example: 10061
sk.close() close socket connection
sk.recv(bufsize[,flag]) Accept socket data. The data is returned as a string, and bufsize specifies the maximum amount that can be received. flag provides additional information about the message and can usually be ignored.
sk.recvfrom(bufsize[.flag]) Similar to recv(), but the return value is (data, address). where data is a string containing the received data and address is the socket address from which the data was sent.
sk.send(string[,flag]) Send the data in string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string. That is: all the specified contents may not be sent.
sk.sendall(string[,flag]) Sends the data in string to the connected socket, but tries to send all the data before returning. Returns None on success, throws an exception on failure. Internally, send everything out by recursively calling send.
sk.sendto(string[,flag],address) Send data to the socket, address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent. This function is mainly used for the UDP protocol.
sk.settimeout(timeout) Sets the timeout period for socket operations, timeout is a floating point number in seconds. A value of None means no timeout period.
sk.getpeername() Returns the remote address of the connected socket. The return value is usually a tuple (ipaddr, port).
sk.getsockname() Returns the socket's own address. Usually a tuple (ipaddr, port)
sk.fileno() file descriptor of the socket

socket programming ideas

TCP server

  1. Create a socket, bind the socket to the local IP and port
  2. start listening for connections
  3. Enter the loop and continuously accept the client's connection request
  4. Then receive the incoming data and send it to the other party
  5. When the transfer is complete, close the socket

TCP client

  1. Create a socket and connect to the remote address
  2. Send and receive data after connecting
  3. When the transfer is complete, close the socket

Create a socket connection

s1.py is the server

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import socket

# 创建一个socket对象
sk = socket.socket()

# 绑定允许连接的IP地址和端口
sk.bind(('127.0.0.1', 6254, ))

# 服务端允许起来之后,限制客户端连接的数量,如果超过五个连接,第六个连接来的时候直接断开第六个。
sk.listen(5)

print("正在等待客户端连接....")
# 会一直阻塞,等待接收客户端的请求,如果有客户端连接会获取两个值,conn=创建的连接,address=客户端的IP和端口
conn, address = sk.accept()
# 输入客户端的连接和客户端的地址信息
print(address, conn)

c1.py is the client

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import socket

# 创建一个socket对象
obj = socket.socket()

# 制定服务端的IP地址和端口
obj.connect(('127.0.0.1', 6254, ))

# 连接完成之后关闭链接
obj.close()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325938803&siteId=291194637