TCP socket发送整形数据(数组,结构体)

使用TCP发送整型等(非字符型)数据时,经常会遇到不能将发送类型转换成const char*的错误。这其实是socket设定的问题,socket设定为只能传送字符型数据。

从read和write的函数生命可以看出,其实发送buffer应该是一个char型指针,所以我们只需要将要发送的数组或者是结构体强制转换成char*就可以了。


Client:


    struct ou_buffer w_buffer;
    w_buffer.a[0] = 1;
    w_buffer.a[1] = 3;
 
    w_buffer.b[0] = 2;
    w_buffer.b[1] = 4;
    w_buffer.b[2] = 6;
    w_buffer.b[3] = 8;
 
    QTcpSocket *tcpSocket = new QTcpSocket;
 
    tcpSocket->abort();
    tcpSocket->connectToHost("192.168.1.102",9734);//Server IP and port.

    qint32 ss[9] = {8,1,2,3,4,5};
 
 
 
    qDebug("CONNECT PROCEDURE...");
    if (tcpSocket->waitForConnected(4000))
        qDebug("Connected!");
    qDebug("\n");

 
    qDebug("WRITE PROCEDURE...");
    //int w = (tcpSocket->write)((char*)&w_buffer, sizeof(w_buffer));//pass
    int w = (tcpSocket->write)((char*)ss, sizeof(ss));//pass
    while(!tcpSocket->waitForBytesWritten(3000)){
        qDebug("sending...");
    }

Server:

while(1){

uint8_t in_buffer[56];
struct in_stu in_buffer2;

printf("server_waiting!\n");

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

int r, w;

printf("reading...\n");
  r = read(client_sockfd, in_buffer, sizeof(in_buffer));
printf("r = %d\n", r);


memcpy(&in_buffer2, in_buffer, sizeof(in_buffer));
printf("in_buffer.a[0] = %d\n", in_buffer2.a[0]);
printf("in_buffer.a[1] = %d\n", in_buffer2.a[1]);
printf("in_buffer.b[0] = %d\n", in_buffer2.b[0]);
printf("in_buffer.b[1] = %d\n", in_buffer2.b[1]);
printf("in_buffer.b[2] = %d\n", in_buffer2.b[2]);
printf("in_buffer.b[3] = %d\n", in_buffer2.b[3]);

...

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值