qscan345server.cpp

Go to the documentation of this file.
00001 #include <QTcpSocket>
00002 #include <QTextStream>
00003 #include "qscan345server.h"
00004 #include "qscan345mainwindow.h"
00005 
00006 QScan345Server::QScan345Server(QScan345MainWindow* win, QObject *parent)
00007   : inherited(parent),
00008     m_MainWindow(win),
00009     m_Socket(NULL)
00010 {
00011   connect(this, SIGNAL(newConnection()),
00012           this, SLOT(openNewConnection()));
00013 
00014   connect (this, SIGNAL(print_message(QString)), 
00015            m_MainWindow, SLOT(display_message(QString)));
00016 }
00017 
00018 void 
00019 QScan345Server::startServer(QHostAddress a, int p)
00020 {
00021   setMaxPendingConnections(1);
00022 
00023   if (isListening()) {
00024     close();
00025   }
00026 
00027   if (!listen(a, p)) {
00028     qWarning("Failed to bind to address %s port %d",
00029              qPrintable(a.toString()), p);
00030   }
00031 }
00032 
00033 void
00034 QScan345Server::openNewConnection()
00035 {
00036   m_Socket = nextPendingConnection();
00037 
00038   connect(m_Socket, SIGNAL(disconnected()),
00039           m_Socket, SLOT(deleteLater()));
00040 
00041   connect(m_Socket, SIGNAL(readyRead()),
00042           this,     SLOT(clientRead()));
00043 
00044   emit print_message(QString("New connection from %1")
00045                      .arg(m_Socket->peerAddress().toString()) );
00046 
00047   connect(m_Socket, SIGNAL(disconnected()),
00048           this,     SLOT(connectionClosed()));
00049 }
00050 
00051 void
00052 QScan345Server::connectionClosed()
00053 {
00054   emit print_message("Client closed connection");
00055 }
00056 
00057 void
00058 QScan345Server::clientRead()
00059 {
00060   QTextStream ts( m_Socket );
00061 
00062   while ( m_Socket->canReadLine() ) {
00063     QString str = ts.readLine();
00064 
00065     emit print_message(tr("Command: %1 received\n").arg(str));
00066     
00067     emit execute_command(str);
00068   }
00069 }
00070 
00071 void
00072 QScan345Server::scan_finished()
00073 {
00074   if (m_Socket && (m_Socket->isWritable())) {
00075     m_Socket -> write("scan finished\n");
00076   }
00077 }
00078 
00079 void
00080 QScan345Server::erase_finished()
00081 {
00082   if (m_Socket && (m_Socket->isWritable())) {
00083     m_Socket -> write("erase finished\n");
00084   }
00085 }