udp socket

3/8/2017来源:ASP.NET技巧人气:3047

import time
from socket import *

HOST = ""
PORT = 9999
BUFSIZE = 1024
ADDR = (HOST, PORT)

udpSerScok = socket(AF_INET, SOCK_DGRAM)
udpSerScok.bind(ADDR)

while True:
    PRint 'waiting for message...'
    data, addr = udpSerScok.recvfrom(BUFSIZE)
    udpSerScok.sendto('[%s] %s'%(time.ctime(), data), addr)
    print 'received from and returned to :' , addr
       
udpSerScok.close()

from socket import *

HOST = 'localhost'
PORT = 9999
BUFSIZE = 1024
ADDR = (HOST, PORT)

udpCliSock = socket(AF_INET, SOCK_DGRAM)

while True:
    data = raw_input('>')
    if not data:
        break
    
    udpCliSock.sendto(data, ADDR)
    data = udpCliSock.recvfrom(BUFSIZE)
    if not data:
        break
    print data
    
tcpCliSock.close()