Connect a socket of TCP/IP on the same machine, R2009b and VC++2008 express SP1
Show older comments
Hello
I tried to connect a TCP/IP socket. Before connect remote machines, I want to test the communication on the same machine.
I tested the socket program with C++ already. And It works properly.
However, when I test same routines on the C-mex file, it downs Matlab.
I wrote down the socket program as like bellows.
----------------------------------------------------------------
--- Server side ---
// Global variables for TCP/IP
int srcSocket; // this program
int dstSocket; // remote program
// sockaddr_in structure
struct sockaddr_in srcAddr;
struct sockaddr_in dstAddr;
int dstAddrSize = sizeof(dstAddr);
int status;
int numrcv;
char buffer[1024];
WSADATA data;
#define MDL_START /* Change to #undef to remove function */
#if defined(MDL_START)
static void mdlStart(SimStruct *S) {
// Initialize socket
WSAStartup(MAKEWORD(2,0), &data);
memset(&srcAddr, 0, sizeof(srcAddr));
srcAddr.sin_port = htons(PORT);
srcAddr.sin_family = AF_INET;
srcAddr.sin_addr.s_addr = htonl(INADDR_ANY); // allow any address to receive data
// open socket, stream type
srcSocket = socket(AF_INET, SOCK_STREAM, 0);
// bind sockek
bind(srcSocket, (struct sockaddr *) &srcAddr, sizeof(srcAddr));
// allow connection
listen(srcSocket, 1);
// accept connection
dstSocket = accept(srcSocket, (struct sockaddr *) &dstAddr, &dstAddrSize);
} #endif /* MDL_START */
--- Client side ---
// Global variables for TCP/IP
char destination[] = "192.168.11.8";
int dstSocket;
struct sockaddr_in dstAddr;
char buffer[1024];
WSADATA data;
#define MDL_START /* Change to #undef to remove function */
#if defined(MDL_START)
static void mdlStart(SimStruct *S) {
WSAStartup(MAKEWORD(2,0), &data);
// Set the structure of sockaddr_in
memset( &dstAddr, 0, sizeof(dstAddr));
dstAddr.sin_port = htons(PORT);
dstAddr.sin_family = AF_INET;
dstAddr.sin_addr.s_addr = inet_addr(destination);
// Create a socket
dstSocket = socket( AF_INET, SOCK_STREAM, 0);
if( connect(dstSocket, (struct sockaddr *) &dstAddr, sizeof(dstAddr)))
{
// Failed to connect
connectCheck = 3;
}
else
{
// Success with connection
connectCheck = 8;
}
}
#endif /* MDL_START */
------------------------------------------------------------------------
I put the server block and the client block on the same model file. Is it the reason of freezing Matlab? I think this is not the good way to initialize the socket between two blocks.
If someone inform me any clue, it would be great help.
Accepted Answer
More Answers (0)
Categories
Find more on TCP/IP Communication in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!