library: io
library part: WebSocketTransformer
import 'dart:io';
main(List<String> args) async {
var server = await HttpServer.bind('127.0.0.1', 8080);
server.listen((HttpRequest req) async {
if (req.uri.path == '/') {
String html = File('browser_websocket.html').readAsStringSync();
req.response.headers.contentType = ContentType.html;
req.response.write(html);
req.response.close();
} else if (req.uri.path == '/ws') {
var socket = await WebSocketTransformer.upgrade(req);
socket.listen((data) => print(data));
} else {
req.response.close();
}
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button>click me</button>
<script>
const websocket = new WebSocket("ws://localhost:8080/ws");
const button = document.querySelector("button");
button.addEventListener("click", () =>
websocket.send("hello from client")
);
</script>
</body>
</html>