zoukankan      html  css  js  c++  java
  • socket 第一课

    基于TCP的socket服务

    server.py

    import socket
    
    sk = socket.socket()
    sk.bind(("127.0.0.1",8080))
    sk.listen()
    
    conn,addr = sk.accept()
    
    while 1:
    
        ret = conn.recv(1024).decode('utf-8')
        if 'bye' in ret:
            conn.send(b'byebye~~')
            break
        print(ret)
    
        info = input('-->: ')
        conn.send(bytes(info,encoding = 'utf-8'))
    
    conn.close()
    sk.close()

    client.py

    import socket
    
    sk = socket.socket()
    
    sk.connect(("127.0.0.1",8080))
    
    while 1:
    
    
        info = input('-->: ')
        sk.send(bytes(info,encoding = 'utf-8',))
    
        ret = sk.recv(1024).decode('utf-8')
        if 'bye' in ret:
            break
        print(ret)
    
    sk.close()

    基于UDP的socket服务

    server.py

    import socket
    
    sk = socket.socket(type=socket.SOCK_DGRAM)
    sk.bind(('127.0.0.1',8080))
    msg, addr = sk.recvfrom(1024)
    
    print(msg.decode('utf-8'))
    sk.sendto(b'byebye~client', addr)
    
    sk.close()

    client.py

    import socket
    
    sk = socket.socket(type=socket.SOCK_DGRAM)
    ip_port = ('127.0.0.1', 8080)
    
    sk.sendto(b'hello server', ip_port)
    ret, addr = sk.recvfrom(1024)
    print(ret.decode('utf-8'))
    
    sk.close()

    udp的server 不需要进行监听,也不需要建立连接

    在启动服务之后只能被动的等待client发送消息

    client发送消息的同时还会自带地址信息

    消息回复的时候不仅需要发送消息,还要把自己的地址发送过去

    tcp相反

  • 相关阅读:
    2015-10-09 Fri 晴 加快进度看书
    lseek()函数
    pipe()管道最基本的IPC机制
    linux VFS 内核数据结构
    tcp协议中mss的理解
    tcp的精髓:滑动窗口
    2015-10-11 Sunday 晴 ARM学习
    2015-10-12 晴 审面包车
    2015-10-14 晴 tcp/ip
    pyfits过滤数据更新文件。
  • 原文地址:https://www.cnblogs.com/Hxx0916/p/9713501.html
Copyright © 2011-2022 走看看