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]);

...

}

你可能感兴趣的:(TCPIP,LINUX,QT,TCPIP,linux,整型)