-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
185 lines (158 loc) · 5.66 KB
/
server.js
File metadata and controls
185 lines (158 loc) · 5.66 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
const express = require("express");
const cors = require("cors");
// App setup
const port = process.env.PORT || 5000
const app = express();
// Configure CORS for Express (for regular HTTP requests) - Allow all origins
app.use(cors({
origin: true, // Allow all origins
credentials: true
}));
// Trust proxy (important for AWS load balancer)
app.set('trust proxy', true);
// Add middleware to log requests for debugging
app.use((req, res, next) => {
console.log(`${req.method} ${req.url} - Origin: ${req.get('Origin')} - IP: ${req.ip}`);
next();
});
// Health check endpoint for load balancer
app.get('/health', (req, res) => {
res.status(200).json({ status: 'healthy', timestamp: new Date().toISOString() });
});
const server = app.listen(port, function () {
console.log(`Listening on port ${port}`);
console.log('Server configured for AWS load balancer with proxy trust enabled');
console.log(`Socket.IO will be available at: http://localhost:${port}/socket.io/`);
});
// Socket setup
const io = require("socket.io")(server, {
cors: {
origin: true, // Allow all origins
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
credentials: true,
preflightContinue: false,
optionsSuccessStatus: 204
},
maxHttpBufferSize: 1e8, // Set the maximum packet size to 100MB
allowEIO3: true, // Allow older clients to connect
transports: ['websocket', 'polling'] // Explicitly allow both transports
});
console.log('Socket.IO server initialized with CORS allowing all origins');
// Add a test endpoint to verify the server is working
app.get('/test', (req, res) => {
res.json({
message: 'Server is running',
socketIOPath: '/socket.io/',
timestamp: new Date().toISOString()
});
});
ID2Socket = {}; // keeps track of all sockets with the same ID
Socket2ID = {}; // keeps track of the ID of each socket
Socket2Type = {};
reserved_messages = [
'connection',
'disconnect',
'ID',
'CameraImgMeta',
'CameraImg',
'ReceiveCameraImgMeta',
'ReceiveCameraImg',
'NeuronCallback',
'log',
'log-warning',
'log-error',
'urchin-loaded-callback',
'urchin-dock-callback'
];
io.on("connection", function (socket) {
console.log("Client connected with ID: " + socket.id + " from origin: " + socket.handshake.headers.origin);
socket.on('disconnect', () => {
console.log('Client disconnected with ID: ' + socket.id);
if (ID2Socket[Socket2ID[socket.id]]) {
ID2Socket[Socket2ID[socket.id]].splice(ID2Socket[Socket2ID[socket.id]].indexOf(socket.id),1);
Socket2ID[socket.id] = undefined;
}
})
socket.on('ID', function(clientData) {
// ID is just a unique identifier, it can be any string
newClientID = clientData[0]
// Type can be "send" or "receive"
newClientType = clientData[1]
console.log('Client ' + socket.id + ' requested to update ID to ' + newClientID);
// Check if we have an old clientID that needs to be removed
if (Socket2ID[socket.id]) {
oldClientID = Socket2ID[socket.id]
ID2Socket[oldClientID].splice(ID2Socket[oldClientID].indexOf(socket.id),1);
}
if (ID2Socket[newClientID] == undefined) {
// save the new entry into a new list
ID2Socket[newClientID] = [socket.id];
}
else {
// save the new entry
ID2Socket[newClientID].push(socket.id);
}
// update the client ID locally
Socket2ID[socket.id] = newClientID;
Socket2Type[socket.id] = newClientType
console.log('User updated their ID to: ' + Socket2ID[socket.id] + " type " + newClientType );
console.log('All connected clients with ID: ' + ID2Socket[Socket2ID[socket.id]]);
});
// Make sure that these receive events are listed in the reserved_messages list
// Camera receive events
socket.on('CameraImgMeta', function(data) {
emitToSender(socket.id, 'CameraImgMeta', data);
});
socket.on('CameraImg', function(data) {
emitToSender(socket.id, 'CameraImg', data);
});
socket.on('ReceiveCameraImgMeta', function(data) {
emitToSender(socket.id, 'ReceiveCameraImgMeta', data);
});
socket.on('ReceiveCameraImg', function(data) {
emitToSender(socket.id, 'ReceiveCameraImg', data);
});
socket.on('NeuronCallback', function(data) {
emitToSender(socket.id, 'NeuronCallback', data);
});
socket.on('urchin-dock-callback', function(data) {
emitToSender(socket.id, 'urchin-dock-callback', data);
});
socket.on('urchin-loaded-callback', function(data) {
emitToSender(socket.id, 'urchin-loaded-callback', data);
});
// Receiver events
socket.on('log', function(data) {
emitToSender(socket.id, 'log', data);
});
socket.on('log-warning', function(data) {
emitToSender(socket.id, 'log-warning', data);
});
socket.on('log-error', function(data) {
emitToSender(socket.id, 'log-error', data);
});
// For all remaining events, asssume they are a sender -> receiver broadcast and emit them automatically
socket.onAny((eventName, data) => {
if (!reserved_messages.includes(eventName)) {
emitToReceiver(socket.id, eventName, data);
}
});
});
function emitToReceiver(id, event, data) {
console.log('Sender sent event: ' + event + ' emitting to all clients with ID: ' + Socket2ID[id] + " and type receive");
for (var socketID of ID2Socket[Socket2ID[id]]) {
if (Socket2Type[socketID]=="receive") {
console.log('Emitting to: ' + socketID);
io.to(socketID).emit(event,data);
}
}
}
function emitToSender(id, event, data) {
console.log('Receiver sent event: ' + event + ' emitting to all clients with ID: ' + Socket2ID[id] + " and type send");
for (var socketID of ID2Socket[Socket2ID[id]]) {
if (Socket2Type[socketID]=="send") {
console.log('Emitting to: ' + socketID);
io.to(socketID).emit(event,data);
}
}
}