美文网首页
041 Python语法之Socket

041 Python语法之Socket

作者: Luo_Luo | 来源:发表于2017-09-12 11:35 被阅读0次

    协议

    1. HTTP
    2. DNS
    3. FTP
    4. SSH
    5. SNMP
    6. ICMP ping
    7. DHCP

    OSI七层

    1. 应用
    2. 表示
    3. 会话
    4. 传输
    5. 网络 IP
    6. 数据链路 MAC
    7. 物理层

    地址簇 Socket Families(网络层)

    1. socket.AF_UNIX unix本机进程间通信
    2. socket.AF_INET IPV4
    3. socket.AF_INET IPV6

    Socket Types

    1. socket.SOCK_STREAM # for tcp
    2. socket.SOCK_DGRAM # for udp
    3. socket.SOCK_RAW # 原始套接字可以处理 ICMP、IGMP等网络报文
    4. socket.SOCK_RDM # 是一种可靠的UDP形式保证数据交互不保证顺序

    TCP

    1. 三次握手,四次断开

    查看端口

    1. netstat -ano # 查看端口占用情况
    2. 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()
    

    相关文章

      网友评论

          本文标题:041 Python语法之Socket

          本文链接:https://www.haomeiwen.com/subject/nyhcsxtx.html