summaryrefslogtreecommitdiffstats
path: root/examples/network/remotecontrol/ipcserver.cpp
blob: a64e70e6bec6791ce263af99e387f3dd93ab6660 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "ipcserver.h"

#include <tqsocket.h>
#include <ntqvariant.h>
#include <tqimage.h>
#include <ntqpalette.h>
#include <ntqapplication.h>

class IpcSocket : public TQSocket
{
    TQ_OBJECT

public:
    IpcSocket( TQObject *parent) : TQSocket( parent )
    {
	packetSize = 0;
	connect( this, TQ_SIGNAL(readyRead()), TQ_SLOT(read()) );
    }

signals:
    void receivedText( const TQString& );
    void receivedPixmap( const TQPixmap& );

private slots:
    void read()
    {
	TQ_ULONG bytesAvail = bytesAvailable();
	for ( ;; ) {
	    if ( packetSize == 0 ) {
		TQDataStream ds( this );
		if ( bytesAvail < 4 )
		    return;
		ds >> packetSize;
		bytesAvail -= 4;
	    } else {
		if ( bytesAvail < packetSize )
		    return;
		// read the packet in a byte array to be sure that you don't
		// read too much or too less
		TQByteArray ba( packetSize );
		readBlock( ba.data(), packetSize );
		bytesAvail -= packetSize;
		packetSize = 0;

		TQVariant variant;
		TQDataStream ds( ba, IO_ReadOnly );
		ds >> variant;
		switch ( variant.type() ) {
		    case TQVariant::String:
			emit receivedText( variant.toString() );
			break;
		    case TQVariant::Image:
			emit receivedPixmap( TQPixmap(variant.toImage()) );
			break;
		    case TQVariant::Palette:
			TQApplication::setPalette( variant.toPalette(), TRUE );
			break;
		    default:
			break;
		}
	    }
	}
    }

private:
    TQ_UINT32 packetSize;
};

IpcServer::IpcServer( TQ_UINT16 port, TQObject *parent ) :
    TQServerSocket( 0x7f000001, port, 1, parent )
{
}

void IpcServer::newConnection( int socket )
{
    IpcSocket *s = new IpcSocket( this );
    s->setSocket( socket );
    connect( s, TQ_SIGNAL(receivedText(const TQString&)),
	    TQ_SIGNAL(receivedText(const TQString&)) );
    connect( s, TQ_SIGNAL(receivedPixmap(const TQPixmap&)),
	    TQ_SIGNAL(receivedPixmap(const TQPixmap&)) );
}

#include "ipcserver.moc"