I am trying to create a websocket connection to a server. However, chrome tells me "WebSocket connection to 'ws://localhost:9898/' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE" in the browser console when I open the html client.
Server: ´´´
const net = require('net');
const server = net.createServer((socket) => {
socket.on('data', (data) => {
console.log(data.toString());
});
socket.write('SERVER: Hello! This is server speaking.\n');
socket.end('SERVER: Closing connection now.\n');
}).on('error', (err) => {
console.error(err);
});
server.listen(9898, () => {
console.log('opened server on', server.address().port);
});
´´´ Client: ´´´
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Playground</title>
</head>
<body>
</body>
<script>
const ws = new WebSocket('ws://localhost:9898');
ws.onerror = function (e) {
console.log('An error occured: \n' + e);
};
ws.onopen = function() {
console.log('WebSocket Client Connected');
ws.send('Hi this is web client.');
};
ws.onmessage = function(e) {
console.log("Received: '" + e.data + "'");
};
</script>
</html>
´´´ Any ideas what could be wrong? Thanks a lot!
Quite embarrassing: My understanding now is that net creates a TCP server. To create a websocket server, I now used the ws package.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.