writing the received data to a text file

允我心安 提交于 2019-12-20 05:26:11

问题


Here is an example of opening a UDP socket in a Mininet host and writing the received packets to a file. h1 acts as a server and h2 acts as a client which is supposed to send a message ( for example "Hello world") to h1. h1 is suppose to receive this message and store the message and address in foo.txt file. But after implementing this code, although foo.txt is created but it's empty and does not contain any data or information. What's wrong?

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()

来源:https://stackoverflow.com/questions/51265502/writing-the-received-data-to-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!