gp443
gp443

Reputation: 267

Python + netcat, only the first message is sent over UDP

I have this snippet of code which acts as a UDP client:

import socket

data = "Hello world!"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print 'sending %s to 127.0.01:9000', data
sent = sock.sendto(data, ('127.0.0.1', 9000))
print 'sent: %s' % sent
sock.close()

And the following is my "server":

nc -u -l 127.0.0.1 9000

This example works... but only once. When I run my script the first time, I send my message over to the server (everything is done o the same machine) and see "Hello world" being printed out. All good. When I run my script a second time, I don't see the second hello world.

Just a heads up, but I'm using Python 2.6, due to circumstances beyond my control.

What is going on here? Is there a buffer that needs to be flushed?

The following happens when I run the code from a Python run-time environment (and no, the results in netcat do not change):

Python 2.6.6 (r266:84292, Aug  9 2016, 06:11:56) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> sent = sock.sendto("Hello world!", ('127.0.0.1', 9000))
>>> print sent
12
>>> sock.close()

Upvotes: 1

Views: 3550

Answers (2)

user7998796
user7998796

Reputation:

Alright. Stop using netcat to test your code. Use this code instead:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('127.0.0.1', 9000))  # (host, port) because AF_INET
print("Listening...")

while True:
    print(sock.recv(15)) # buffer size

You may change host, port and buffer size according to your case.

Upvotes: 2

Related Questions