The socket network programming Python3

What is Socket?

Socket also known as "sockets", the application is usually issued by the "socket" network request or response to network requests, the process between the hosts or between a computer can communicate.

Socket workflow

Socket object (built-in) method

function description
Server-side socket
s.bind() Binding address (host, port) to the socket, at AF_INET, expressed as a tuple address (host, port) of.
s.listen() TCP start listening. backlog specified before connection rejection, the operating system can suspend the maximum number of connections. The value of at least 1, most of the application is set to 5 on it.
s.accept() Passively accept TCP client connections (blocking) waiting for the arrival of
Client socket
s.connect() Initiative initialize TCP server connections. The general format of address tuples (hostname, port), if the connection error, an error return socket.error.
s.connect_ex() connect () function is an extended version returns an error code if an error occurs, rather than throwing an exception
Public use socket functions
s.recv() Receiving TCP data, returned as a string, the maximum amount of data to be received bufsize specified. flag provides additional information about the message can usually be ignored.
s.send() TCP data transmission, the transmission data string is attached to the socket. The return value is the number of bytes to be transmitted, this number may be smaller than the size in bytes of the string.
s.sendall() Complete TCP send data, send TCP data integrity. The transmission data string is connected to the socket, but before returning tries to send all the data. Successful return None, failure exception is thrown.
s.recvfrom() Receiving UDP data, the recv () is similar, but the return value is (data, address). Wherein the received data is a string containing the data, address data is the address of the sending socket.
s.sendto() UDP data transmission, transmits the data to the socket, the form of address (ipaddr, port) tuple, the specified remote address. The return value is the number of bytes sent.
s.close() Closes the socket
s.getpeername() 返回连接套接字的远程地址。返回值通常是元组(ipaddr,port)。
s.getsockname() 返回套接字自己的地址。通常是一个元组(ipaddr,port)
s.setsockopt(level,optname,value) 设置给定套接字选项的值。
s.getsockopt(level,optname[.buflen]) 返回套接字选项的值。
s.settimeout(timeout) 设置套接字操作的超时期,timeout是一个浮点数,单位是秒。值为None表示没有超时期。一般,超时期应该在刚创建套接字时设置,因为它们可能用于连接的操作(如connect())
s.gettimeout() 返回当前超时期的值,单位是秒,如果没有设置超时期,则返回None。
s.fileno() 返回套接字的文件描述符。
s.setblocking(flag) 如果flag为0,则将套接字设为非阻塞模式,否则将套接字设为阻塞模式(默认值)。非阻塞模式下,如果调用recv()没有发现任何数据,或send()调用无法立即发送数据,那么将引起socket.error异常。
s.makefile() 创建一个与该套接字相关连的文件

 

一个简单服务器实例 socketserver.py:

 1 import socket
 2 
 3 # 创建 socket 对象,使用IPV4 和 TCP连接
 4 serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 5 
 6 # 绑定地址端口号 ,这里填的 本机地址 和 随便一个端口号
 7 serversocket.bind(('127.0.0.1', 52003))
 8 
 9 # 设置最大连接数,超过后排队
10 serversocket.listen(5)
11 
12 while True:
13     # 建立客户端连接
14     clientsocket, addr = serversocket.accept()
15 
16     print("连接地址: %s" % str(addr))
17 
18     msg = '来自socket服务器!' + "\r\n"
19     clientsocket.send(msg.encode('utf-8'))
20     clientsocket.close()

客户端实例 socketclient.py:

 1 import socket
 2 
 3 # 创建 socket 对象
 4 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 5 
 6 # 连接服务,指定主机和端口
 7 s.connect(('127.0.0.1', 52003))
 8 
 9 # 接收小于 1024 字节的数据
10 msg = s.recv(1024)
11 
12 s.close()
13 
14 print (msg.decode('utf-8'))

先运行 socketserver.py , 再运行 socketclient.py,

socketserver.py 输出:

连接地址: ('127.0.0.1', 56042)

 socketclient.py 输出:

来自socket服务器!

转载于:https://www.cnblogs.com/jxu25/p/11006254.html

Guess you like

Origin blog.csdn.net/weixin_33725807/article/details/93643138