TCP/IP communication between C + + and matlab based on linux

        For a project related to iiwa, C + + and matlab are needed for real-time data communication. The data transmission only needs the joint angle and spatial coordinate attitude of the robot (double array with length of 7)

        Since most of the functions are implemented in matlab and called by C + +, the Server side is implemented in matlab and the client side is implemented in C + +.

         The code is as follows:

Client (C + +)

#define MAXLINE 4096
#define IP  ""

	double joint[6]={10.123456,11.123456,12.123456,13.123456,14.123456,15.123456};
	double joint1[7]={0};
	const int len_double = sizeof(double);

void *dtoc(void *s,char *m,size_t n)//Convert double type to char type
	char *ss = s;

	for (int i = 0; i < n; i++)
	return m;

void btos(char *s)//Small end mode: low byte in low order and high byte in high address
	char send_arr[len_double];
	for(int j=0;j<7;j++){
		for(int i=0;i<len_double;i++){
		for(int i=0;i<len_double;i++){

void *ctod(void *s,double *m,size_t n)//Convert char type to double type
	double *ss = s;

	for (int i = 0; i < 7; i++)
	return m;

int main(){
    int   sockfd, n;
    char  recvline[4096], sendline[4096];
    struct sockaddr_in  servaddr;

    //Create a socket
    if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
        printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);
        return 0;

    //Initialize to bind the serial port number and other information
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("");
    servaddr.sin_port = htons(6668);

    //Actively connect to the server 
    if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){
        printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
        return 0;

    printf("Connection succeeded\n");

     int num=0;
//     while(1){

         printf("send msg to server: \n");




         send(sockfd, sendline, strlen(sendline), 0);

             //strlen: calculates the character length by subtracting the first address from the last address of the number of character arrays
        // if( send(sockfd, sendline, strlen(sendline), 0) < 0){
        //    printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
        //      return 0;
        //  } 
          recv(sockfd, recvline, MAXLINE, 0);
 	for(int i=0;i<7;i++){
         	printf(" %f ", joint1[i]);
//     }

    return 0;

         Explain the above code: the code is mainly divided into two parts. 1. Communicate with the server from Matlab. 2. Convert the target array into a form convenient for transmission and reading.

        1. Communicate with the server from Matlab. Adopt traditional TCP (socket communication)

The server first initializes the socket, then binds it to the port, listens to the port, calls accept to block, and waits for the client to connect.

socket() -> bind() -> listen() -> accept()

The client first initializes the socket and then connects with the server. If the server listens successfully, the connection is established

socket() -> connect()

         2. Convert the target array into a form convenient for transmission and reading.

The format of data transmission is char (it is said that c + + transmission can only use char, which should be verified in theory after some time), and small end mode (low byte in low order and high byte in high order)

The conversion part has two points: 1. Convert the double precision array into char type and char type into double precision type; 2. Convert data format to small end format. dtoc and ctod functions, and btos functions, respectively.

Server (Matlab)

t_server=tcpip('',6668,'NetworkRole','server');%Establish a connection with the first client requesting a connection, with port number 6668 and type server.
t_server.InputBuffersize=10000;%Enlarge the buffer to 10000
fopen(t_server);%Open the server until one is established TCP Return only after connection;
sprintf("The connection was established successfully");

    while(1)%Wait until there is data in the cache to jump out of the loop
     if  t_server.BytesAvailable>0
         %t_server.BytesAvailable%Displays the number of cache bytes
data_recv=(fread(t_server,t_server.BytesAvailable));%Read digital data from buffer

send1=num2hex(data_send);%Convert to hexadecimal

for j = 1:length(data_send)
    send2 = [send2,send1(j,:)]; %Small end mode

count1 = 0;
send3 = []; %Convert into double
while count1 < length(data_send)*8
    send3 = [send3,hex2dec(send2((count1*2+1):(count1*2+2)))];
    count1 = count1 + 1;



%%%%Incoming char Convert array to double type%%%%
recv1 = dec2hex(data_recv);%ACSII Convert code to hexadecimal

recv2 = [];                      %Put data together in small end form
for i = 1:length(recv1)
    recv2 = [recv2,recv1(i,:)]; %Small end mode

%Convert into double
count = 0;
recv3 = []; 
while count < length(recv1)/8
    recv3 = [recv3,hex2num(recv2((count*16+1):(count*16+16)))];
    count = count + 1;

%%%take double Type conversion char array%%%%%%
send1=num2hex(data_send);%Convert to hexadecimal

for j = 1:length(data_send)
    send2 = [send2,send1(j,:)]; %Small end mode

%Convert into double
count1 = 0;
send3 = []; 
while count1 < length(data_send)*8
    send3 = [send3,hex2dec(send2((count1*2+1):(count1*2+2)))];
    count1 = count1 + 1;

         In addition to the TCP connection, the Matlab part is mainly about converting the char array passed in from C + + into double type, converting the double type into char type and then transmitting it to C + +. The conversion principle is that after converting the decimal number to hexadecimal, put it together in small end mode, and then divide it according to the required data type, and then return to the decimal number.

Reference: TCP/IP communication between Visual Studio C + + and Matlab to transfer double type data

                        Linux C/C++ TCP Socket communication example Etc;

New article, if there are mistakes and omissions, welcome the boss to point out.

Tags: C++ Linux MATLAB

Posted on Mon, 01 Nov 2021 03:26:53 -0400 by prabhuksmani