本文实例讲述了python实现简单socket程序在两台电脑之间传输消息的方法。分享给大家供大家参考。具体分析如下:
python开发简单socket程序在两台电脑之间传输消息,分为客户端和服务端,分别在两台电脑上运行后即可进行简单的消息传输,也可以在一台电脑上测试,设置两个不同的端口即可。
# Save as server.py 服务端代码# Message Receiverimport osfrom socket import *host = ""port = 13000buf = 1024addr = (host, port)UDPSock = socket(AF_INET, SOCK_DGRAM)UDPSock.bind(addr)print "Waiting to receive messages..."while True: (data, addr) = UDPSock.recvfrom(buf) print "Received message: " + data if data == "exit": breakUDPSock.close()os._exit(0) # Save as client.py 客户端代码# Message Senderimport osfrom socket import *host = "127.0.0.1" # set to IP address of target computerport = 13000addr = (host, port)UDPSock = socket(AF_INET, SOCK_DGRAM)while True: data = raw_input("Enter message to send or type 'exit': ") UDPSock.sendto(data, addr) if data == "exit": breakUDPSock.close()os._exit(0)
希望本文所述对大家的Python程序设计有所帮助。
新闻热点
疑难解答
图片精选