Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UDP socket via JavaScript in a browser

Can I open a UDP socket via javascript in browser?

I know that websocket only uses TCP and the only thing that uses UDP in browser is WebRTC.

Is there any other way? Can I use WebAssembly to compile c++ that uses UDP socket?

I tried to compile this code to WebAssembly:

int main(int argc, char *argv[])
{
//initialize socket and structure
int socket_info;
struct sockaddr_in server;
char message[100];
char incoming_message[100];

printf("Input Message: ");
fgets(message, 100, stdin);

    //create socket
    socket_info = socket(AF_INET, SOCK_DGRAM, 0);
    if (socket_info == -1) {
    printf("Could not create socket");
    }

//assign local values
    server.sin_addr.s_addr = inet_addr("172.21.8.178");
    server.sin_family = AF_INET;
    server.sin_port = htons( 1100 );

    //binds connection
    if (bind(socket_info, (struct sockaddr *)&server, sizeof(server)) < 0) {    
perror("Connection error");
       return 1;
    }
    puts("Bind");

    //assign new value to connect to
    server.sin_addr.s_addr = inet_addr("192.118.68.1");

    //checks connection 
    if (connect(socket_info, (struct sockaddr *)&server, sizeof(server)) <       0) {
    perror("Connection error");
       return 1;
    }
    puts("Connected");

    //sends message
if(send(socket_info, message, strlen(message), 0) <0) {        
perror("Send failed");
    return 1;
    }
    puts("Message Sent");

//receives message back    
if(recv(socket_info, incoming_message, sizeof(incoming_message), 0) <0) {    
puts("Received failed");
    return 1;
    }
    puts("Message received");
    puts(incoming_message);

close(socket_info);

}

No luck. :(

like image 240
avi dahan Avatar asked Oct 22 '17 10:10

avi dahan


1 Answers

No, browsers do not support UDP. Also, WebAssembly doesn’t have any APIs for communication - to access any network APIs you would have to do this by exposing JavaScript functions to your WebAssembly module.

I think your only option is to adapt your UDP messages to WebSocket. There are commercial products that do this, such as the Kaazing gateway (https://kaazing.com/), there may be open source alternatives.

like image 127
ColinE Avatar answered Oct 10 '22 01:10

ColinE