这里是在Mininet主机中打开UDP套接字并将接收到的数据包写入文件的示例。 h1充当服务器,h2充当客户端,该客户端应该向h1发送消息(例如“ Hello world”)。 h1假定接收此消息并将消息和地址存储在foo.txt文件中。 但是在执行此代码后,尽管创建了foo.txt,但它为空并且不包含任何数据或信息。怎么了?
mininetSocketTest.py:
#!/usr/bin/python
from mininet.topo import Topo, SingleSwitchTopo
from mininet.net import Mininet
from mininet.log import lg, info
from mininet.cli import CLI
def main():
lg.setLogLevel('info')
net = Mininet(SingleSwitchTopo(k=2))
net.start()
h1 = net.get('h1')
p1 = h1.popen('python myServer.py -i %s &' % h1.IP())
h2 = net.get('h2')
h2.cmd('python myClient.py -i %s -m "hello world"' % h1.IP())
CLI( net )
p1.terminate()
net.stop()
if __name__ == '__main__':
main()
myClient.py:
import socket, optparse
parser = optparse.OptionParser()
parser.add_option('-i', dest='ip', default='127.0.0.1')
parser.add_option('-p', dest='port', type='int', default=12345)
parser.add_option('-m', dest='msg')
(options, args) = parser.parse_args()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(options.msg, (options.ip, options.port) )
myServer.py:
import socket, optparse
parser = optparse.OptionParser()
parser.add_option('-i', dest='ip', default='')
parser.add_option('-p', dest='port', type='int', default=12345)
(options, args) = parser.parse_args()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind( (options.ip, options.port) )
f = open('foo.txt','w')
while True:
data, addr = s.recvfrom(512)
f.write("%s: %s\n" % (addr, data))
f.flush()