简体   繁体   中英

Matlab 2012 to Visual Studio 2013 UDP Communication

I need to build communication between Matlab version 2012 and Visual Studio version 2013 with UDP protocol.


Matlab Installed Computer will be my Server

Visual Studio 2013 Installed Computer will be my Client


Basic Operation

I have to send continiously text files from MATLAB and received at Visual Studio 2013.


Operating Systems

Matlab OS : Mac OSX 10.10 and Visual Sudio 2013 OS : Windows 10.


I am going to use UDP protocol between them and send integer values from MATLAB to Visual Studio.


I tried this kind of communication, between 2 computers, both of them have Visual Studio installed, and I successfully send bytes between them.


Unfortunately I couldn't establish communication between MATLAB and Visual Studio.

Client Code

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>


// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")


#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(int argc, char **argv)
{
   WSADATA wsaData;
   SOCKET ConnectSocket = INVALID_SOCKET;
   struct addrinfo *result = NULL,
    *ptr = NULL,
    hints;
   char *sendbuf = "(!)Hello, I'm Client Lenovo Z570";
   char recvbuf[DEFAULT_BUFLEN];
   int iResult;
   int recvbuflen = DEFAULT_BUFLEN;

   // Validate the parameters
   if (argc != 2) {
       printf("\n\n\n\t\t\tusage: %s server-name\n\n\n\t\t\t", argv[0]);
       system("pause");
       return 1;
   }

   // Initialize Winsock
   iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
   if (iResult != 0) {
       printf("\n\n\n\t\t\tWSAStartup failed with error: %d\n\n       \n\t\t\t", iResult);
    system("pause");
    return 1;
}

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
    printf("\n\n\n\t\t\tgetaddrinfo failed with error: %d\n\n\n\t\t\t", iResult);
    WSACleanup();
    system("pause");
    return 1;
}

// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

    // Create a SOCKET for connecting to server
    ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
        ptr->ai_protocol);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("\n\n\n\t\t\tsocket failed with error: %ld\n\n\n\t\t\t", WSAGetLastError());
        WSACleanup();
        system("pause");
        return 1;
    }

    // Connect to server.
    iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        closesocket(ConnectSocket);
        ConnectSocket = INVALID_SOCKET;
        continue;
    }
    break;
}

freeaddrinfo(result);

if (ConnectSocket == INVALID_SOCKET) {
    printf("\n\n\n\t\t\tUnable to connect to server!\n\n\n\t\t\t");
    WSACleanup();
    system("pause");
    return 1;
}

// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
    printf("\n\n\n\t\t\tsend failed with error: %d\n\n\n\t\t\t", WSAGetLastError());
    closesocket(ConnectSocket);
    WSACleanup();
    system("pause");
    return 1;
}

printf("\n\n\n\t\t\tBytes Sent: %ld\n\n\n\t\t\t", iResult);

// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
    printf("\n\n\n\t\t\tshutdown failed with error: %d\n\n\n\t\t\t", WSAGetLastError());
    closesocket(ConnectSocket);
    WSACleanup();
    system("pause");
    return 1;
}

// Receive until the peer closes the connection
do {

    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {
        printf("\n\n\n\t\t\tBytes received: %d\n\n\n\t\t\t", iResult);

        printf("\n\n\n\t\t\tContent of the Received Packet:\n\n\n\t\t\t ");
        for (int i = 0; i < sizeof(recvbuf); i++){
            if (isascii(recvbuf[i])){
                putchar(recvbuf[i]);
            }
        }
    }
    else if (iResult == 0)
        printf("\n\n\n\t\t\tConnection closed\n\n\n\t\t\t");
    else
        printf("\n\n\n\t\t\trecv failed with error: %d\n\n\n\t\t\t", WSAGetLastError());

} while (iResult > 0);

// cleanup
closesocket(ConnectSocket);
WSACleanup();
system("pause");
return 0;
}

About Using Code

I found this code on Microsoft website. Before Launching the code I set up the IP address of Server.

在此处输入图片说明

Error

The code gave me the error "Unable to Connect Server!"

Could you please help me?

Any idea will be appreciated. Thanks.

I hope the following example will help anyone, who is willing to learn udp sending. Following Code will work both ethernet and wifi connections.

The code connect to 27015 port of the sender. For example you want to connect 8888 port then change

unsigned short Port = 27015; to unsigned short Port = 8888;

#ifndef UNICODE
#define UNICODE
#endif

#define WIN32_LEAN_AND_MEAN

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>

// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

int main()
{

int iResult = 0;

WSADATA wsaData;

SOCKET RecvSocket;
sockaddr_in RecvAddr;

unsigned short Port = 27015;

char RecvBuf[1024];
int BufLen = 1024;

sockaddr_in SenderAddr;
int SenderAddrSize = sizeof (SenderAddr);

//-----------------------------------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
    wprintf(L"WSAStartup failed with error %d\n", iResult);
    return 1;
}
//-----------------------------------------------
// Create a receiver socket to receive datagrams
RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (RecvSocket == INVALID_SOCKET) {
    wprintf(L"socket failed with error %d\n", WSAGetLastError());
    return 1;
}
//-----------------------------------------------
// Bind the socket to any address and the specified port.
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);

iResult = bind(RecvSocket, (SOCKADDR *) & RecvAddr, sizeof (RecvAddr));
if (iResult != 0) {
    wprintf(L"bind failed with error %d\n", WSAGetLastError());
    return 1;
}
//-----------------------------------------------
// Call the recvfrom function to receive datagrams
// on the bound socket.
wprintf(L"Receiving datagrams...\n");
iResult = recvfrom(RecvSocket,
                   RecvBuf, BufLen, 0, (SOCKADDR *) & SenderAddr,  &SenderAddrSize);
if (iResult == SOCKET_ERROR) {
    wprintf(L"recvfrom failed with error %d\n", WSAGetLastError());
}

//-----------------------------------------------
// Close the socket when finished receiving datagrams
wprintf(L"Finished receiving. Closing socket.\n");
iResult = closesocket(RecvSocket);
if (iResult == SOCKET_ERROR) {
    wprintf(L"closesocket failed with error %d\n", WSAGetLastError());
    return 1;
}

//-----------------------------------------------
// Clean up and exit.
wprintf(L"Exiting.\n");
WSACleanup();
return 0;
}  

PS If you want to connect to the specific IP address change

RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);

code into for example Assume your IP is 192.168.2.1 then

RecvAddr.sin_addr.s_addr = inet_addr("192.168.2.1");

If you still have question, don't hesitate feel free to ask, If I know it; I will answer it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM