您的位置:首页 > 编程语言 > Python开发

[转] 最简单的使用UDP通信的Python Socket例子

2009-09-27 22:09 1141 查看
来源:http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/

客户端程序代码:

# Client program
from socket import *
# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "/n",def_msg
# Send messages
while (1):
data = raw_input('>> ')
if not data:
break
else:
if(UDPSock.sendto(data,addr)):
print "Sending message '",data,"'....."
# Close socket
UDPSock.close()


服务器端程序代码:

# Server program
from socket import *
# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
data,addr = UDPSock.recvfrom(buf)
if not data:
print "Client has exited!"
break
else:
print "/nReceived message '", data,"'"
# Close socket
UDPSock.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: