Linux套接字与Qt 4中的QTcpSockets通信

时间:2009-06-28 23:17:23

标签: linux qt tcp qt4

我正在尝试在Qt程序和常规Linux程序之间与TCP通信。我有一个现有的Linux客户端服务器程序,我试图用Qt应用程序替换服务器程序。这是linux客户端代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <unistd.h>

int main(int argc, char *argv[])
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buffer[256];

    portno = 9876;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if (sockfd < 0) 
    {
       printf("ERROR opening socket");
       return -1;
    }
    server = gethostbyname("localhost");

    if (server == NULL) 
    {
        printf("ERROR, no such host\n");
        return -1;
    }

    memset((char *) &serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);

    connect(sockfd,(sockaddr*)&serv_addr,sizeof(serv_addr));

    sprintf(buffer,"This is a test\n");
    n = write(sockfd,buffer,256);

    return 0;
}

这是qt代码

#include <Qt>
#include <QApplication>
#include <QTcpServer>
#include <QMessageBox>
#include <QTcpSocket>
#include <QtNetwork>

#include "qtserver.h"


Server::Server()
{
   tcp = new QTcpServer(this);
   tcp->listen(QHostAddress::Any,9876);
   QObject::connect(tcp,SIGNAL(newConnection()),this,SLOT(printline()));
}

void Server::printline()
{
   QTcpSocket *client = tcp->nextPendingConnection();
   QObject::connect(client,SIGNAL(disconnected()),
                    client,SLOT(deleteLater()));


   QDataStream in(client);
   in.setVersion(QDataStream::Qt_4_0);

   QString data;
   in >> data;
   printf("String = %s\n",(char*)data.data());
}

int main(int argc,char** argv)
{
   QApplication a(argc,argv);

   Server* server = new Server();

   return a.exec();
}

当我尝试运行它们时,我只得到“String =”而不是字符串输出。知道我做错了吗?

1 个答案:

答案 0 :(得分:3)

QString::data()返回QChar *,你不能只将它转换为char *并希望它始终有效。要调试QString,请改用qPrintable

此外,QTcpSocket非常易于使用。不过,不是从头开始编写代码,为什么不从签出示例开始,例如Fortune Server示例。