协议
- HTTP
- DNS
- FTP
- SSH
- SNMP
- ICMP ping
- DHCP
OSI七层
- 应用
- 表示
- 会话
- 传输
- 网络 IP
- 数据链路 MAC
- 物理层
地址簇 Socket Families(网络层)
- socket.AF_UNIX unix本机进程间通信
- socket.AF_INET IPV4
- socket.AF_INET IPV6
Socket Types
- socket.SOCK_STREAM # for tcp
- socket.SOCK_DGRAM # for udp
- socket.SOCK_RAW # 原始套接字可以处理 ICMP、IGMP等网络报文
- socket.SOCK_RDM # 是一种可靠的UDP形式保证数据交互不保证顺序
TCP
- 三次握手,四次断开
查看端口
- netstat -ano # 查看端口占用情况
- netstat -aon|findstr "9050" # 查看端口占用情况
Server
import socket
socketServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socketServer.bind(("localhost", 8888)) # 这里必须传入一个元组
socketServer.listen(5)
while True:
clientSocket, address = socketServer.accept()
print("客户端连接上了")
bytes1 = clientSocket.recv(1024)
print("接收消息:", str(bytes1, encoding="utf-8", errors="strict"))
myStr = input("发送信息:")
clientSocket.send(bytes(myStr, encoding="utf-8", errors="strict"))
serverSocket.close()
Client
import socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect(("localhost", 8888))
while True:
myStr = input("请输入消息")
clientSocket.send(myStr.encode(encoding="utf-8", errors="strict"))
bytes = clientSocket.recv(1024)
print(str(bytes, encoding="utf-8", errors="strict"))
clientSocket.close()
UDP
Server
import socket
udpserver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpserver.bind(("192.168.23.1", 8848))
while True:
data, addr = udpserver.recvfrom(1024)
message = str(data, encoding="utf-8", errors="ignore")
print("来自", addr, "消息", message)
udpserver.close()
Client
import socket
# socket.AF_INET
# socket.SOCK_DGRAM
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
mystr = input("你想说啥:")
udp.sendto(mystr.encode("utf-8", errors="ignore"), ("127.0.0.1", 8848))
print(udp.recv(1024).decode("utf-8")) # 收消息
udp.close()
网友评论