qavrg 0.0.28
qavrgserver.cpp
Go to the documentation of this file.
00001 #include "qavrgserver.h"
00002 
00003 #include <QTcpSocket>
00004 #include <QTextStream>
00005 #include "qavrgscriptingengine.h"
00006 
00007 QavrgServer::QavrgServer(QObject *parent)
00008   : inherited(parent),
00009     m_Socket(NULL)
00010 {
00011   connect(this, SIGNAL(newConnection()),
00012           this, SLOT(openNewConnection()));
00013 }
00014 
00015 void
00016 QavrgServer::startServer(QHostAddress addr, int port)
00017 {
00018   setMaxPendingConnections(1);
00019 
00020   if (isListening()) {
00021     close();
00022   }
00023 
00024   if (!listen(addr, port)) {
00025     emit printMessage(tr("Failed to bind to address %1 port %2")
00026                       .arg(addr.toString()).arg(port));
00027   }
00028 }
00029 
00030 void
00031 QavrgServer::openNewConnection()
00032 {
00033   m_Socket = nextPendingConnection();
00034 
00035   connect(m_Socket, SIGNAL(disconnected()),
00036           m_Socket, SLOT(deleteLater()));
00037 
00038   connect(m_Socket, SIGNAL(readyRead()),
00039           this,     SLOT(clientRead()));
00040 
00041   emit printMessage(tr("New connection from %1")
00042                      .arg(m_Socket->peerAddress().toString()) );
00043 
00044   connect(m_Socket, SIGNAL(disconnected()),
00045           this,     SLOT(connectionClosed()));
00046 }
00047 
00048 void
00049 QavrgServer::connectionClosed()
00050 {
00051   emit printMessage("Client closed connection");
00052 }
00053 
00054 void
00055 QavrgServer::clientRead()
00056 {
00057   QTextStream ts( m_Socket );
00058 
00059   while ( m_Socket->canReadLine() ) {
00060     QString str = ts.readLine();
00061 
00062     emit printMessage(tr("Command: %1 received").arg(str));
00063     
00064     emit executeCommand(str);
00065   }
00066 }
00067 
00068 void
00069 QavrgServer::finishedCommand(QScriptValue result)
00070 {
00071   emit printMessage(tr("Result: %1").arg(result.toString()));
00072 
00073   if (m_Socket && (m_Socket->isWritable())) {
00074     m_Socket -> write(qPrintable(result.toString()));
00075   }
00076 }