想詢問如何用 Dart 建立 Websocket Server,希望可以多Client同時連線
當 Server 發送訊息時,連線中的Client也可以同時收到訊息
查了很多資料,都是使用別的方法建立Server,實在不知道如何同時傳到連線中的 Client
目前只能傳到最後一個連線的 Client
在此附上Server與Client的程式碼~
目前是想在3個 Client 連線後,用 Server 傳送訊息到 Client
以上,希望有人能幫忙,謝謝!
Server.Dart
import 'dart:io';
void main() {
HttpServer.bind("192.168.87.6", 4040).then((HttpServer server) {
print("HttpServer listening...");
print('Listening on localhost:${server.port}');
server.serverHeader = "DartEcho (1.0)";
server.listen((HttpRequest request) {
if (WebSocketTransformer.isUpgradeRequest(request)) {
print(request.uri.path);
WebSocketTransformer.upgrade(request).then(handleWebSocket);
} else {
print("Regular ${request.method} request for: ${request.uri.path}");
serveRequest(request);
}
});
});
}
int a = 0;
int r = 0;
void handleWebSocket(WebSocket socket) {
print('Client connected!');
a += 1;
if (a >= 3) {
print("已連線裝置" + a.toString());
while (r == 0) {
print('請輸入數字[開始錄影(1)/停止錄影(2)]: ');
final doing = stdin.readLineSync();
// socket.forEach((doing) {
if (doing.toString() == "1") {
socket.add("start");
} else if (doing.toString() == "2") {
socket.add("stop");
} else {
socket.add(doing);
}
}
}
}
void serveRequest(HttpRequest request) {
request.response.statusCode = HttpStatus.FORBIDDEN;
request.response.reasonPhrase = "WebSocket connections only";
request.response.close();
}
Client1.Dart
import 'dart:async';
import 'dart:io';
Future main() async {
final socket = await WebSocket.connect('ws://192.168.87.6:4040/1');//利用這邊區別Client
print('Connected to server!');
socket.asBroadcastStream().listen((message) {
if (message == "start") {
print('$message:開始錄影');
} else if (message == "stop") {
print('$message:錄影暫停');
} else {
print(message);
}
}, onDone: () {
print("Done");
});
}
Client2.Dart
import 'dart:io';
Future main() async {
final socket = await WebSocket.connect('ws://192.168.87.6:4040/2');
print('Connected to server!');
socket.listen((message) {
if (message == "start") {
print('$message:開始錄影');
} else if (message == "stop") {
print('$message:錄影暫停');
}
}, onDone: () {
print("Done");
});
}
使用 Dart 的 dart:io 套件
import 'dart:io';
void main() {
HttpServer.bind('0.0.0.0', 4040).then((HttpServer server) {
print('Listening on ${server.address}:${server.port}');
server.transform(WebSocketTransformer()).listen(handleWebSocket);
});
}
final List<WebSocket> sockets = [];
void handleWebSocket(WebSocket socket) {
sockets.add(socket);
print('New WebSocket connection.');
socket.listen((dynamic data) {
print('Received data: $data');
sockets.forEach((s) {
s.add(data);
});
}, onDone: () {
print('WebSocket closed.');
sockets.remove(socket);
});
}
目前是想在3個 Client 連線後,用 Server 傳送訊息到 Client
socket.add('Hello, world!');