python udp简单示例

#udpClient.py
#!/usr/bin/env python
from socket import *
ADDR = ('127.0.0.1', 3000)
udpCliSock = socket(AF_INET, SOCK_DGRAM)
udpCliSock.settimeout(3)
while True:  
    data = raw_input('>>>>')
    if cmp(data,'end') == 0:
        break
    udpCliSock.sendto(data,ADDR)
    print '--> ',ADDR,data
    try:
        data,address = udpCliSock.recvfrom(2048)
        print '<-- ',address,data
    except:
        pass
udpCliSock.close()
 
  
#udpServer.py
#!/usr/bin/env python  
# -*- coding:UTF-8 -*-
from socket import *
ADDR = ('127.0.0.1',3000)###127.0.0.1 代表本地IP,3000是通信端口
udpServer = socket(AF_INET, SOCK_DGRAM)  
udpServer.bind(ADDR)  
udpServer.settimeout(5)  #设置超时
while True:
    try:
        data, addr = udpServer.recvfrom(2048)
        print "<-- ",addr,data
        udpServer.sendto("Server received message!!",addr)
        print "--> ",addr,"Server received message!!"
    except:
        pass
udpServer.close()

你可能感兴趣的:(Python)