summaryrefslogtreecommitdiffstats
path: root/kbattleship/kbattleship/kbattleshipclient.cpp
blob: d895e934cd4b194929d4110a8bbe5a5539b2c9f1 (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
/***************************************************************************
                            kbattleshipclient.cpp
                             -------------------
    Developers: (c) 2000-2001 Nikolas Zimmermann <wildfox@kde.org>
                (c) 2000-2001 Daniel Molkentin <molkentin@kde.org>

 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <unistd.h>
#ifdef HAVE_STROPTS_H
#include <stropts.h>
#endif
#ifdef HAVE_SYS_FILIO_H
#include <sys/filio.h>
#endif
#include <sys/ioctl.h>
#include <tqsocketnotifier.h>
#include "kmessage.h"
#include "kbattleshipclient.moc"

KBattleshipClient::KBattleshipClient(const TQString &host, int port) : KExtendedSocket(host, port, inetSocket)
{
}

void KBattleshipClient::init()
{
	if(connect())
	{
		emit sigSocketFailure(status());
		return;
	}

	m_readNotifier = new TQSocketNotifier(fd(), TQSocketNotifier::Read, TQT_TQOBJECT(this));
	TQT_BASE_OBJECT_NAME::connect(m_readNotifier, TQT_SIGNAL(activated(int)), TQT_SLOT(slotReadData()));
	emit sigConnected();
}

void KBattleshipClient::sendMessage(KMessage *msg)
{
	TQCString post = msg->sendStream().utf8();
	writeBlock(post.data(), post.length());
	emit sigMessageSent(msg);
}

void KBattleshipClient::slotReadData()
{
	int len;
	ioctl(fd(), FIONREAD, &len);
	if(!len)
	{
		delete m_readNotifier;
		m_readNotifier = 0;
		emit sigEndConnect();
		return;
	}

	char *buf = new char[len + 1];
	readBlock(buf, len);
	buf[len] = 0;
	m_readBuffer += TQString::fromUtf8(buf);
	delete []buf;
	int pos;
	while ((pos = m_readBuffer.find("</kmessage>")) >= 0)
	{
		pos += 11; // Length of "</kmessage>"
		KMessage *msg = new KMessage();
		msg->setDataStream(m_readBuffer.left(pos));
		m_readBuffer.remove(0, pos);
		emit sigNewMessage(msg);
	}
}