简体   繁体   中英

Qt Server Client Code

I am a new to the QT programming. my server/client codes are quite simple but they are not working.......

pls have a look to find problems in my codes, thanks.

SERVER:

int main(int argc, char** argv)
{
//  QApplication app(argc, argv);
//      Server server;
        QTcpSocket *client_sock =  NULL;
        QTcpServer server;
        server.listen(QHostAddress::Any,8888);
        char buff[100];

    while(1)
    {
            if(server.hasPendingConnections())
            {
                    client_sock = server.nextPendingConnection();
            }
            if(client_sock)
            {
                    qint64 n_rtn;
                    n_rtn = client_sock->bytesAvailable();
                    client_sock->readLine(buff,n_rtn);
                    std::cout<<buff;
            }
    }
//  return app.exec();
}

CLIENT:

int main(int argc, char** argv)
{
//  QApplication app(argc, argv);
  QTcpSocket client;
  QHostAddress addr("127.0.0.1");
  client.connectToHost(addr,8888);

  if(client.isWritable())
  {
        client.write("Hello World!\n");
  }

  client.close();

//  return app.exec();
}

Thanks

Without a QApplication or a QCoreApplication and an app.exec() nothing will work. This is what runs the event loop which handles all the keyboard/mouse/network events.

Take a look at the chat and fortune cookie network server examples to see how to do this - it's almost as simple as the code you have written

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM