This repository has been archived by the owner on Sep 23, 2024. It is now read-only.
forked from TypeFox/monaco-languageclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
57 lines (55 loc) · 2.24 KB
/
server.ts
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
/* --------------------------------------------------------------------------------------------
* Copyright (c) 2018-2022 TypeFox GmbH (http://www.typefox.io). All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import { WebSocketServer } from 'ws';
import { IncomingMessage } from 'http';
import { URL } from 'url';
import { Socket } from 'net';
import express from 'express';
import { IWebSocket } from 'vscode-ws-jsonrpc';
import { launch } from './json-server-launcher.js';
import { getLocalDirectory } from './fs-utils.js';
process.on('uncaughtException', function(err: any) {
console.error('Uncaught Exception: ', err.toString());
if (err.stack) {
console.error(err.stack);
}
});
// create the express application
const app = express();
// server the static content, i.e. index.html
app.use(express.static(getLocalDirectory()));
// start the server
const server = app.listen(3000);
// create the web socket
const wss = new WebSocketServer({
noServer: true,
perMessageDeflate: false
});
server.on('upgrade', (request: IncomingMessage, socket: Socket, head: Buffer) => {
const baseURL = `http://${request.headers.host}/`;
const pathname = request.url ? new URL(request.url, baseURL).pathname : undefined;
if (pathname === '/sampleServer') {
wss.handleUpgrade(request, socket, head, webSocket => {
const socket: IWebSocket = {
send: content => webSocket.send(content, error => {
console.log(content);
if (error) {
throw error;
}
}),
onMessage: cb => webSocket.on('message', cb),
onError: cb => webSocket.on('error', cb),
onClose: cb => webSocket.on('close', cb),
dispose: () => webSocket.close()
};
// launch the server when the web socket is opened
if (webSocket.readyState === webSocket.OPEN) {
launch(socket);
} else {
webSocket.on('open', () => launch(socket));
}
});
}
});