QT client和linux服务器示例小程序

闲来无事,发现一贴在网上的某个QT写的TCPIP的示例小程序,遂运行一下发现不通过。

研究了一下,发现是client发数据过快(还没握手成功就发了数据),遂修改一下,并转换成以windows下QT为client,linux 下写的server.代码简单,初级,仅供参考。

Client:

#include
#include
#include
#include
#include
#include
#include

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug("/***************************/");
    qDebug("this is a tcp test project!");
    qDebug("/***************************/\n");

    QTcpSocket *tcpSocket = new QTcpSocket;

    tcpSocket->abort();
    tcpSocket->connectToHost("192.168.1.102",9734);//Server IP and port.

    char ss = 'h';
    char aa = 's';
    qDebug("Original, aa = %c\n", aa);
    qDebug("\n");

    qDebug("CONNECT PROCEDURE...");
    if (tcpSocket->waitForConnected(4000))
        qDebug("Connected!");
    qDebug("\n");

    qDebug("WRITE PROCEDURE...");
    int w = (tcpSocket->write)(&ss, 1);
    while(!tcpSocket->waitForBytesWritten(3000)){
        qDebug("sending...");
    }
    qDebug("w = %d", w);
    qDebug("\n");

    qDebug("READ PROCEDURE...");
    while(!tcpSocket->waitForReadyRead(3000));
    int r = (tcpSocket->read)(&aa,1);
    qDebug("r = %d", r);
    qDebug("aa = %c", aa);
    qDebug("\n");

    return 0;
}

Server:

#include
#include
#include
#include
#include
#include
#include


int main(int argc, char* argv[])
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;

server_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(9734);
server_len = sizeof(server_address);
int d = bind(server_sockfd, (struct sockaddr*)&server_address, server_len);

listen(server_sockfd, 5);

while(1){
char ch = 'a';
printf("\n\n");
printf("server_waiting!\n");

client_len = sizeof(client_address);

client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_address, &client_len);

printf("original: ch = %c\n", ch);
int r, w;

  r = read(client_sockfd, &ch, 1);
printf("reading...\n");
printf("r = %d\n", r);
printf("rcv ch = %c\n", ch);
printf("\n");

w = write(client_sockfd, &ch, 1);
printf("sending...\n");
printf("w = %d\n", w);
printf("snd ch = %c\n", ch);
close(client_sockfd);
}

}

NOTE: 1. 此处简单读写一个字符,多个字符或其他数据更改也比较简单,此处不详细修改;

     2. QT QTcpSocket编程时,读写最好都使用waitForConnected、 waitForReadyRead、waitForBytesWritten等来判断,以免无法同步。 

你可能感兴趣的:(TCPIP)