UdpSocket.py 1.53 KB
"""
@author Georg Hopp

"""
import socket

import Transport
from Socket import Socket, CONTINUE

class UdpSocket(Socket):
    def __init__(self, host, port, con_ttl=30):
        super(UdpSocket, self).__init__(host, port, socket.SOCK_DGRAM, con_ttl)

    """
    TODO: recv and send are pretty similar to the TcpSocket implementation.
    It might be a good idea to unify them into the Socket class.
    Think about this.
    At the end it seems that from the application programmer perspective
    there is not really much difference between Udp and Tcp Sockets...well
    I guess thats the whole idea behind the Socket API... :D
    """
    def recv(self, size):
        data_remote = None
        try:
            data_remote = self.socket.recvfrom(size)
        except socket.error as error:
            if error.errno not in CONTINUE:
                raise Transport.Error(Transport.Error.ERR_FAILED)
            return None

        if not data_remote:
            raise Transport.Error(Transport.Error.ERR_REMOTE_CLOSE)

        return data_remote

    def send(self, data, remote):
        send = 0
        try:
            if self.socket:
                send = self.socket.sendto(data, remote)
        except socket.error as error:
            if error.errno not in CONTINUE:
                if error.errno == errno.ECONNRESET:
                    raise Transport.Error(Transport.Error.ERR_REMOTE_CLOSE)
                else:
                    raise Transport.Error(Transport.Error.ERR_FAILED)

        return send

# vim: set ft=python et ts=4 sw=4 sts=4: