-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy pathdata-channels.c
72 lines (63 loc) · 1.88 KB
/
data-channels.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
#include "webrtc.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
void on_data_channel(GoDataChannel d);
void on_open(GoDataChannel d);
void on_message(GoDataChannel d, struct GoDataChannelMessage msg);
char *rand_seq(int n);
int main()
{
// Register data channel creation handling
GoRun(on_data_channel);
}
void on_data_channel(GoDataChannel d)
{
// Register channel opening handling
GoOnOpen(d, on_open);
// Register text message handling
GoOnMessage(d, on_message);
}
void on_open(GoDataChannel d)
{
char *label = GoLabel(d);
// d = DataChannel.ID() since we pass this from Go
printf("Data channel '%s'-'%d' open. Random messages will now be sent to any connected DataChannels every 5 seconds\n", label, d);
free(label);
while (1)
{
sleep(5);
char *message = rand_seq(15);
printf("Sending '%s'\n", message);
// Send the message as text
GoSendText(d, message);
free(message);
}
}
void on_message(GoDataChannel d, struct GoDataChannelMessage msg)
{
char *label = GoLabel(d);
printf("Message from DataChannel '%s': '%s'\n", label, (char *)(msg.data));
// since we use C.CBytes and C.CString to convert label and msg.data,
// the converted data are allocated using malloc. So, we need to free them.
// Reference: https://golang.org/cmd/cgo/#hdr-Go_references_to_C
free(label);
free(msg.data);
}
char *rand_seq(int n)
{
srand(time(0));
char letters[52] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int n_letters = sizeof(letters) / sizeof(char);
char *b = malloc(sizeof(char) * (n + 1));
for (int i = 0; i < n; i++)
{
b[i] = letters[rand() % n_letters];
}
b[n] = '\0';
return b;
}