/*************************************************************************** * Copyright (C) 1980-2005 Artur Wiebe * * artur@wiebenet.de * * * * 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. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "serversocket.h" #include "config.h" #include myServerSocket::myServerSocket(int port) : QServerSocket(port, 1) { m_server = m_client = 0; } myServerSocket::~myServerSocket() { if(m_server) delete m_server; if(m_client) delete m_client; } void myServerSocket::newConnection(int fd) { mySocket* socket = new mySocket(this); socket->setSocket(fd); QServerSocket::connect(socket, SIGNAL(readyRead()), this, SLOT(slotReadClient())); QServerSocket::connect(socket, SIGNAL(connectionClosed()), this, SLOT(slotClientDisconnected())); } void myServerSocket::slotClientDisconnected() { mySocket* s = (mySocket*)sender(); rm_socket(s); } void myServerSocket::slotReadClient() { mySocket* s = (mySocket*)sender(); while(s && s->canReadLine()) { QString line = s->readLine(); QString kw = line.left(KW_LEN); QString data = line.mid(KW_LEN, line.length()-KW_LEN-1); if(kw==S_VER) { if(data == QString(APPNAME VERSION)) send(s, C_ACK); else send(s, C_NACK); } else if(kw==S_HELP) { send(s, QString(APPNAME" "VERSION)); } else if(kw==S_CREATE) { if(!m_server) { m_server = s; s->setType(mySocket::tServer); send(s, C_ACK); } else send(s, C_NACK); } else if(kw==S_JOIN) { if(m_server && !m_client) { m_client = s; s->setType(mySocket::tClient); // s->setOther(m_server); m_server->setOther(m_client); // send(s, C_ACK); } else send(s, C_NACK); } else if(kw==S_DATA) { send(s->other(), data); } else if(kw==S_DISC) { rm_socket(s); return; } else { qDebug("S.unknown command(%s)", kw.latin1()); delete s; } } } void myServerSocket::send(mySocket* socket, const QString& data) { if(!socket) return; QString line = data + NETWORK_NL; int len = socket->writeBlock(line.latin1(), line.length()); socket->flush(); if(len < 0) { qDebug("myServerSocket::sendText: failed."); return; } if((unsigned int)len != line.length()) { qDebug("myServerSocket::sendText (wanted/sent)(%d,%d", line.length(), len); return; } } void myServerSocket::rm_socket(mySocket* s) { if(s==m_client || s==m_server) { if(s->other()) delete s->other(); delete s; m_client = m_server = 0; } }