summaryrefslogtreecommitdiff
path: root/common/udpovertcp.py
blob: f99b2b36304f3b14751c3177f463d3d578d8a3d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from socket import *
from .msgstruct import *
#from fcntl import ioctl
#from termios import TIOCOUTQ
from zlib import compressobj, Z_SYNC_FLUSH
import struct

ZeroBuffer = struct.pack("i", 0)


class SocketMarshaller:
    
    def __init__(self, tcpsock, mixer):
        self.tcpsock = tcpsock
        self.mixer   = mixer
        self.mixer_can_mix = mixer.send_can_mix
        self.mixer_send    = mixer.send_buffer
        self.tcpsock_fd = tcpsock.fileno()
        # try to reduce TCP latency
        try:
            tcpsock.setsockopt(SOL_IP, IP_TOS, 0x10)  # IPTOS_LOWDELAY
        except error as e:
            print("Cannot set IPTOS_LOWDELAY for client:", str(e))
        try:
            tcpsock.setsockopt(SOL_TCP, TCP_NODELAY, 1)
        except error as e:
            print("Cannot set TCP_NODELAY for client:", str(e))
        compressor = compressobj(6)
        self.compress = compressor.compress
        self.compress_flush = compressor.flush
    
    def send(self, data):
        if self.mixer_can_mix():
            # discard all packets if there is still data waiting in tcpsock
            # --- mmmh, works much better without this check ---
            #try:
            #    if ioctl(self.tcpsock_fd, TIOCOUTQ, ZeroBuffer) != ZeroBuffer:
            #        return
            #except IOError, e:
            #    print "ioctl(TIOCOUTQ) failed, disconnecting client"
            #    self.mixer.disconnect(e)
            #else:
                data = self.compress(data) + self.compress_flush(Z_SYNC_FLUSH)
                self.mixer_send(message(MSG_INLINE_FRAME, data))
                return len(data)
        return 0