美文网首页
python udp

python udp

作者: 极速魔法 | 来源:发表于2017-12-31 16:10 被阅读30次

    python udp

    server.py

    # -*-coding:utf-8 -*-
    
    import socket
    import sys
    HOST=''
    PORT=8888
    
    try:
        s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        print('socket created')
    except socket.error:
        print('created failed')
        sys.exit()
    
    #bind socket
    try:
        s.bind((HOST,PORT))
    except socket.error:
        print('bind failed')
    
    print('bind ok')
    
    #keep talking with client
    while True:
        #server receive and send
        d=s.recvfrom(1024)
        data=d[0]
        addr=d[1]
    
        if not data:
            break
        reply='ok...'+data.decode('utf-8')
    
        s.sendto(reply.encode('utf-8'),addr)
        print('message[' +addr[0]+':'+str(addr[1])+']-'+data.strip())
    s.close()
    
    
    

    client.py

    # -*-coding:utf-8 -*-
    
    import socket
    import sys
    
    #create dgram udp socket
    try:
        s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    except socket.error:
        print('create udp failed')
        sys.exit()
    
    host='localhost'
    port=8888
    
    while True:
        msg='this is client'
    
        try:
            #client send and receive
            s.sendto(msg.encode('utf-8'),(host,port))
    
            d=s.recvfrom(1024)
            reply=d[0]
            addr=d[1]
    
            print('server reply:'+reply.decode('utf-8'))
        except socket.error:
            print('client error')
            sys.exit()
    
    

    相关文章

      网友评论

          本文标题:python udp

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