1 | /*************************************************************************** |
2 | * KBlocks, a falling blocks game for KDE * |
3 | * Copyright (C) 2010 Zhongjie Cai <squall.leonhart.cai@gmail.com> * |
4 | * * |
5 | * This program is free software; you can redistribute it and/or modify * |
6 | * it under the terms of the GNU General Public License as published by * |
7 | * the Free Software Foundation; either version 2 of the License, or * |
8 | * (at your option) any later version. * |
9 | ***************************************************************************/ |
10 | #include "KBlocksNetClient.h" |
11 | |
12 | KBlocksNetClient::KBlocksNetClient(const QString& remoteIP, quint16 localPort) |
13 | { |
14 | mLocalAddress = QHostAddress::Any; |
15 | mLocalPort = localPort; |
16 | |
17 | parseIPString(remoteIP, &mRemoteAddress, &mRemotePort); |
18 | |
19 | mpClientSocket = new QUdpSocket(this); |
20 | mpClientSocket->bind(mLocalAddress, mLocalPort); |
21 | connect(mpClientSocket, SIGNAL(readyRead()), this, SLOT(receivedData())); |
22 | } |
23 | |
24 | KBlocksNetClient::~KBlocksNetClient() |
25 | { |
26 | delete mpClientSocket; |
27 | } |
28 | |
29 | int KBlocksNetClient::sendData(int count, char * data) |
30 | { |
31 | int ret = mpClientSocket->writeDatagram(data, count, mRemoteAddress, mRemotePort); |
32 | if (ret < 0) |
33 | { |
34 | printf("Send error\n" ); |
35 | } |
36 | return ret; |
37 | } |
38 | |
39 | int KBlocksNetClient::recvData(int count, char * data) |
40 | { |
41 | if (!mpClientSocket->hasPendingDatagrams()) |
42 | { |
43 | return -1; |
44 | } |
45 | return mpClientSocket->readDatagram(data, count); |
46 | } |
47 | |
48 | bool KBlocksNetClient::parseIPString(const QString& input, QHostAddress * ip, quint16 * port) |
49 | { |
50 | bool result = false; |
51 | ip->setAddress(input.left(input.indexOf(":" ))); |
52 | *port = input.mid(input.indexOf(":" ) + 1).toUInt(&result); |
53 | return result; |
54 | } |
55 | |
56 | void KBlocksNetClient::receivedData() |
57 | { |
58 | emit(dataArrived(mpClientSocket->pendingDatagramSize())); |
59 | } |
60 | |