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
|
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Mozilla Bug</title>
<script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
</head>
<body>
<script>
"use strict";
window.onload = function() {
const CC = Components.Constructor;
const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm");
const WebSocketServer = require("devtools/server/socket/websocket-server");
const ServerSocket = CC("@mozilla.org/network/server-socket;1",
"nsIServerSocket", "init");
add_task(async function() {
// Create a TCP server on auto-assigned port
const server = new ServerSocket(-1, true, -1);
ok(server, `Launched WebSocket server on port ${server.port}`);
let input, output;
server.asyncListen({
async onSocketAccepted(socket, transport) {
info("Accepted incoming connection");
input = transport.openInputStream(0, 0, 0);
output = transport.openOutputStream(0, 0, 0);
// Perform the WebSocket handshake
const webSocket = await WebSocketServer.accept(transport, input, output);
// Echo the received message back to the sender
webSocket.onmessage = ({ data }) => {
info("Server received message, echoing back");
webSocket.send(data);
};
},
onStopListening(socket, status) {
info(`Server stopped listening with status: ${status}`);
},
});
SimpleTest.registerCleanupFunction(() => {
server.close();
});
// Create client connection
const client = await new Promise((resolve, reject) => {
const socket = new WebSocket(`ws://localhost:${server.port}`);
socket.onopen = () => resolve(socket);
socket.onerror = reject;
});
ok(client, `Created WebSocket connection to port ${server.port}`);
// Create a promise that resolves when the WebSocket closes
const closed = new Promise(resolve => {
client.onclose = resolve;
});
// Send a message
const message = "hello there";
client.send(message);
info("Sent a message to server");
// Check that it was echoed
const echoedMessage = await new Promise((resolve, reject) => {
client.onmessage = ({ data }) => resolve(data);
client.onerror = reject;
});
is(echoedMessage, message, "Echoed message matches");
// Close the connection
client.close();
await closed;
// Prevent leaking the streams by closing them before test ends
input.close();
output.close();
});
};
</script>
</body>
</html>
|