This code sets up a Socket.IO server and client for testing, handling potential port conflicts by retrying server startup if necessary.
npm run import -- "Check if sockify server is running"
var tryReset = false;
try {
var io = sockifyServer(8098);
} catch (e) {
if (e.code !== 'EADDRINUSE') {
throw e;
} else {
tryReset = true;
}
}
var fs = sockifyClient(require('fs'), 'fs', 'http://localhost:8098');
if (tryReset) {
fs.___close();
var io = sockifyServer(8098);
}
// Import required modules
const fs = require('fs');
const { createServer } = require('http');
// Define constants
const LISTEN_PORT = 8098;
const FS_ENDPOINT = `http://localhost:${LISTEN_PORT}`;
/**
* Attempt to start the server at port LISTEN_PORT.
* If the port is in use, the function will catch the error, set tryReset to true, and exit.
*
* @returns {Server} The server instance if the port is available.
* @throws {Error} If the port is unavailable but the error code is not EADDRINUSE.
*/
function startServer() {
try {
return createServer().listen(LISTEN_PORT);
} catch (e) {
if (e.code!== 'EADDRINUSE') {
throw e;
} else {
return null;
}
}
}
// Initialize server and file system
let tryReset = false;
let io = startServer();
if (!io) {
tryReset = true;
}
// Create a file system client connected to the server at FS_ENDPOINT
const client = require('./sockifyClient')(fs, 'fs', FS_ENDPOINT);
if (tryReset) {
// If the port is in use, close the client and restart the server
client.close();
io = startServer();
io.listen(LISTEN_PORT);
}
This code snippet sets up a mock Socket.IO server and client for testing purposes.
Here's a breakdown:
Server Setup:
sockifyServer(8098)
.EADDRINUSE
errors (which indicate the port is already in use).tryReset
to true
, indicating a retry attempt.Client Setup:
fs
module using sockifyClient(require('fs'), 'fs', 'http://localhost:8098')
. This means it's mocking the fs
module's interactions with the Socket.IO server.Retry Server:
tryReset
is true
(meaning the port was initially in use), it closes the mock client (fs.___close()
) and tries to start the Socket.IO server again on port 8098.In essence:
This code aims to create a reliable test environment by handling potential port conflicts and ensuring a working Socket.IO server and client for testing purposes.