python开发简单socket程序在两台电脑之间传输消息,分为客户端和服务端,分别在两台电脑上运行后即可进行简单的消息传输,也可以在一台电脑上测试,设置两个不同的端口即可。
代码语言:javascript复制# Save as server.py 服务端代码 - sharejs.com
Message Receiver
import os
from socket import *
host = ""
port = 13000
buf = 1024
addr = (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":
break
UDPSock.close()
os._exit(0)
Save as client.py 客户端代码 - sharejs.com
Message Sender
import os
from socket import *
host = "127.0.0.1" # set to IP address of target computer
port = 13000
addr = (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":
break
UDPSock.close()
os._exit(0)</pre>