sockt 知识点:
(1)TCP/IP (三次握手,四次挥手):https://www.cnblogs.com/Qing-840/p/9283367.html
(2)协议:(http、smtp、dns、ftp、ssh、snmp、dhcp)(应用层)、icmp ping(网络层)
所有协议都必须两个动作,send 和 recieve( 就是socket)
(3)OSI:物理层、数据链路层( mac)、网络层 ip、传输层、会话层、表示层、应用层
(4)ip(32位):
port(16位 65535个):
0-1023:系统端口
1024-49151:登记端口
49152-65535:短暂端口
sockt模块:
(1)Socket Families(地址簇)
socket. AF_UNIX unix 本机进程间通信
socket. AF_INET IPV4
socket. AF_INET6 IPV6
(2)Type:
socket.SOCK_STREAMs 流式socket , for TCP (默认)
ocket.SOCK_GRAM 数据报式socket , for UDP
(3)服务端:
(1)选择连接模式,创建socket对象,地址蔟/
(2)绑定ip端口
(3)监听端口
(4)等待
(5)发送接收
(6)关闭
(4)客户端:
(1)选择连接模式,创建socket对象
(2)连接ip及端口号
(3)发送接收
(4)关闭
(5)bytes -> str:
(1) str(b,encording = ‘编码‘)
(2) bytes.decode(b) 或 b.decode(‘utf-8‘)
(6)str -> bytes:
(1)bytes(s,encording = ‘编码‘)
(2)str.encord(s) 或 s.encord(‘utf-8‘)
代码区:
import socket
class SOCKserver(object):
def __init__(self,ip = ‘127.0.0.1‘,port = 9999):
self.server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.server.bind((ip,port))
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.listen(5)
self.connection()
def connection(self):
while True:
conn, addr = self.server.accept()
print("a new link for ", addr)
while True:
try:
data = conn.recv(1024)
if data:
print(‘recv data [%s]‘%data)
conn.send(data)
else:
print("lost the link")
conn.close()
break
except ConnectionResetError as e:
print("lost the link")
conn.close()
break
if __name__ == ‘__main__‘:
s = SOCKserver()
import socket
conn = socket.socket()
conn.connect((‘localhost‘,9999))
while True:
com =input(">>:")
conn.send(com.encode())
print(conn.recv(1024))
socketserver模块:
(1)首先,您必须创建一个请求处理程序类,处理程序类继承BaseRequestHandlerclass并覆盖它的handle()方法;
这个方法将处理传入的请求。
(2)其次,您必须实例化其中一个服务器类(TCP、UDP.......),并将服务器的地址和请求处理程序类传递给它。
(3)然后调用服务器对象的handle_request() 或serve_forever()方法来处理一个或多个请求。
最后,调用server_close()关闭套接字
import socketserver
class MyTCPHandle(socketserver.BaseRequestHandler):
def handle(self):
while True:
try:
self.data = self.request.recv(1024)
if self.data:
# print("{} wrote:".format(self.client_address[0]))
print(self.data.decode())
self.request.send(b"recv sucessful!")
except ConnectionResetError as e:
print("%s client is lost!"%self.client_address[0])
break
if __name__ == "__main__":
HOST,PORT = "0.0.0.0",9999
# server = socketserver.TCPServer((HOST,PORT),MyTCPHandle)
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandle)
# print(server.allow_reuse_address)
server.serve_forever()
原文:https://www.cnblogs.com/gtq7512/p/11438046.html