Cara menggunakan python recv vs recvfrom

This is an example, test it with netcat (nc -u localhost 8888) on linux (ubuntu 9.10).
Lauch it with python , a prompt will appear.
Type "start" to launch the server, test the server sending UDP packets with netcat, the lenght of packet will be correctly printed.
However, when you'll type "stop" the close will be invoked but the receiving thread wont stop and the join in the stop() wont never return and you will need to kill the python interpreter.


import socket
import threading
import sys
import select


class UDPServer:
    def __init__(self):
        self.s=None
        self.t=None
    def start(self,port=8888):
        if not self.s:
            self.s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.s.bind(("",port))
            self.t=threading.Thread(target=self.run)
            self.t.start()
    def stop(self):
        if self.s:
            self.s.close()
            self.t.join()
            self.t=None
    def run(self):
        while True:
            try:
                data,addr=self.s.recvfrom(1024)
                print "recv done"
                if len(data)<=0:
                    raise
                self.onPacket(addr,data)
            except:
                break
        #chiusura socket
        print "server is no more running"
        self.s=None
    def onPacket(self,addr,data):
        print len(data)


us=UDPServer()
while True:
    sys.stdout.write("UDP server> ")
    cmd=sys.stdin.readline()
    if cmd=="start\n":
        print "starting server..."
        us.start(8888)
        print "done"
    elif cmd=="stop\n":
        print "stopping server..."
        us.stop()
        print "done"
    elif cmd=="quit\n":
        print "Quitting ..."
        us.stop()
        break;

print "bye bye"

The recv method receives up to buffersize bytes from the socket. When no data is available, it blocks until at least one byte is available or until the remote end is closed. When the remote end is closed and all data is read, it returns an empty byte string.

What does RECV mean in Python?

recv is the maximum length of the message to read at once. It will try to read up to that number, but no more, then return the read value.

What is socket recv ()?

The recv() function receives data on a socket with descriptor socket and stores it in a buffer. The recv() call applies only to connected sockets.

What is the use of socket Recvfrom () method in python?

The recvfrom() method Python’s socket class, reads a number of bytes sent from an UDP socket. Like sendto(), the recvfrom() method as well is to be called on a UDP socket. Unlike sendto(), the method recvfrom() does not take an IP address and port as a parameter.

Is recv blocking calls?

recv(IPC, Buffer, int n) is a blocking call, that is, if data is available it writes it to the buffer and immediately returns true, and if no data is available it waits for at least n seconds to receive any data.

What is the difference between RECV and Recvfrom?

The recvfrom() system call receives a message from a socket and capture the address from which the data was sent. Unlike the recv() call, which can only be used on a connected stream socket or bound datagram socket, recvfrom() can be used to receive data on a socket whether or not it is connected.

Does recv wait for data?

Now in the last call to recv, it would block till it gets CHUNK_SIZE amount of data or a default timeout occurs which can be from 30 seconds to 1 minute. This can be too much of waiting for an application.

What’s the difference between RECV and read?

The only difference between recv() and read(2) is the presence of flags. With a zero flags argument, recv() is generally equivalent to read(2) (but see NOTES).

How do I stop RECV from waiting?

If you want to stop the recv completely, you should be using select with a timeout to wait until data is available. You can then check whether you should keep waiting for data or continue at each timeout.

Is socket recv blocking C?

In short: yes, it is blocking. But not in the way you think. recv() blocks until any data is readable.

What does Recvfrom return?

Return value If no error occurs, recvfrom returns the number of bytes received. If the connection has been gracefully closed, the return value is zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.

Can I use recv with UDP?

Similarly, you would normally use recvfrom() to know where the UDP data was received from. However, you can actually use connect() on UDP socket as an option. In that case, you can use send()/recv() on the UDP socket to send data to the address specified with the connect() and to receive data only from the address.

How do I interrupt RECV?

To interrupt the thread, make the socket non-blocking (set O_NONBLOCK using fcntl ) and then signal the thread with pthread_kill . This way, recv will fail with either EINTR if it was sleeping, or EAGAIN or EWOULDBLOCK if it wasn’t (also maybe if SA_RESTART is in effect, didn’t check).

Does recv wait?

The recv() call can be used on a connection mode socket or a bound, connectionless socket. If no messages are available at the socket, the recv() call waits for a message to arrive unless the socket is nonblocking.