MATLAB uses mex to compile C++ socket communication

Development environment :
System: window7 64-bit
MATLAB: 2019a 64-bit
VS: 2019
Summary : This blog mainly implements the use of VS2019 to write Socket server C++ code, MATLAB uses mex to compile C++ code, and finally generates a mexw64 file that can be run on MATLAB, MATLAB Start the mexw64 file to realize socket communication.

1. Socket communication C++ code writing
Reference blog:
(1) Socket communication code of Window system: http://c.biancheng.net/cpp/html/3031.html
(2) VS configuration MATLAB development environment blog:
https:// blog.csdn.net/bingbingshui90/article/details/75376717?locationNum=6&fps=1
Socket server code written in VS

#include <iostream>
#include "mex.h"
#include <stdio.h>
#include <winsock2.h>
#pragma comment (lib,"ws2_32.lib")


using namespace std;
void socketServer();
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
    
    
	socketServer();


}
void socketServer()
{
    
    
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);

	SOCKET servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	sockaddr_in sockAddr;
	memset(&sockAddr, 0, sizeof(sockAddr));
	sockAddr.sin_family = PF_INET;
	sockAddr.sin_addr.s_addr = inet_addr("192.168.1.17");
	sockAddr.sin_port = htons(7000);
	bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));

	listen(servSock, 20);
	SOCKADDR clntAddr;
	int nSize = sizeof(SOCKADDR);
	SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize);

	const char* str = "hello World";
	send(clntSock, str, strlen(str) + sizeof(char), NULL);

	closesocket(clntSock);
	closesocket(servSock);

	WSACleanup();
	
}

2. Compile C++ code with MATLAB mex
(1) Choose a compiler
If mex is not installed, install mex first, and search and install it directly in MATLAB.

mex -setup

Select the compiler according to the prompt
insert image description here
(2) copy the C++ code file to the current MATLAB working directory

(3) Input command

mex  SocketBase.cpp -lwsock32

Among them, SocketBase.cpp is a C++ code file.
After the compilation is completed, you can use the command: SocketBase to start (the same SocketBase is the file name of the compiled mexw64 file)

Guess you like

Origin blog.csdn.net/yyl80/article/details/106659580