我一直在尝试学习足够的html,css和Dart来创建我的第一个网页,一切顺利, 除了 ,我不明白如何创建一个简单的页面和服务器端的Web套接字服务器,它将回显它。我发现的示例倾向于说明其他Dart工具,并连接到网络上的echo服务器或做其他使他们的代码对新手来说不简单的事情。
我试图将Seth Ladd的example“dart-example-web-sockets-client”简化为“最佳”示例。我可以接收从页面发送的内容,重新打包并认为我将其发送回去,但网页上没有任何反应。我通过单击从Dart编辑器内部运行Web服务器时返回的URL来启动页面。由于页面不是,AFAIK,在调试器中运行,我在诊断错误时遇到了阻碍。
以下是Seth服务器的简化代码:
void handleEchoWebSocket(WebSocket webSocket) {
log.info('New WebSocket connection');
// Listen for incoming data. We expect the data to be a JSON-encoded String.
webSocket
.map((string) => JSON.decode(string))
.listen((json) {
// The JSON object should contain a 'request' entry.
var request = json['request'];
switch (request) {
case 'search':
var input = json['input'];
log.info("Received request '$request' for '$input'");
var response = {
'response': request,
'input': input,
};
webSocket.add(JSON.encode(response)); // can't detect page receiving this.
log.info("Echoed request..$request $input"); // correct data
break;
default:
log.warning("Invalid request: '$request'");
}
}, onError: (error) {
log.warning('Bad WebSocket request');
});
}
此示例使用用户输入作为两个搜索引擎的输入,打包结果并将它们返回到页面以便在运行中创建新的DOM元素。
我只需要指出一个简单的例子来回应提交的内容。
答案 0 :(得分:8)
这是一个简单的websocket客户端/服务器回显示例。消息不会显示在浏览器窗口中,但会在控制台窗口中打印。您必须分别启动server.dart和main.dart。两个进程都将消息打印到自己的控制台窗口。 编辑:我添加了一个输出div,用于在浏览器中显示消息。
仓\ ws_server.dart:
import "dart:convert";
import 'dart:io';
import 'package:route/server.dart' show Router;
void handleWebSocket(WebSocket webSocket) {
// Listen for incoming data. We expect the data to be a JSON-encoded String.
webSocket
.map((string)=> JSON.decode(string))
.listen((json) {
// The JSON object should contains a 'echo' entry.
var echo = json['echo'];
print("Message to be echoed: $echo");
var response='{"response": "$echo"}';
webSocket.add(response);
}, onError: (error) {
print('Bad WebSocket request');
});
}
void main() {
int port = 9223;
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, port).then((server) {
print("Search server is running on "
"'http://${server.address.address}:$port/'");
var router = new Router(server);
// The client will connect using a WebSocket. Upgrade requests to '/ws' and
// forward them to 'handleWebSocket'.
router.serve('/ws')
.transform(new WebSocketTransformer())
.listen(handleWebSocket);
});
}
幅\ index.html的:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Websocket echo</title>
</head>
<body>
<p>Websocket test</p>
<div id="output"></div>
<script type="application/dart" src="main.dart"></script>
</body>
</html>
幅\ main.dart:
library main;
import 'dart:async';
import 'dart:convert';
import 'dart:html';
class WebsocketService {
WebSocket webSocket;
WebsocketService() {
connect();
}
void connect() {
webSocket = new WebSocket('ws://127.0.0.1:9223/ws');
webSocket.onOpen.first.then((_) {
onConnected();
sendws("Hello websocket server");
webSocket.onClose.first.then((_) {
print("Connection disconnected to ${webSocket.url}");
onDisconnected();
});
});
webSocket.onError.first.then((_) {
print("Failed to connect to ${webSocket.url}. "
"Please run bin/server.dart and try again.");
onDisconnected();
});
}
void onConnected() {
webSocket.onMessage.listen((e) {
onMessage(e.data);
});
}
void onDisconnected() {
print("Disconnected, trying again in 3s");
new Timer(new Duration(seconds:3), (){
connect();
});
}
void onMessage(data) {
var json = JSON.decode(data);
var echoFromServer = json['response'];
print("Received message: $echoFromServer");
var output=querySelector('#output');
output.text="Received message: $echoFromServer";
new Timer(new Duration(seconds:3), (){ //Send a new message to server after 3s
String now = new DateTime.now().toString();
sendws("Time: $now");
});
}
void sendws(String msg){
var request = '{"echo": "$msg"}';
print("Send message to server: $request");
webSocket.send(request);
}
}
void main() {
WebsocketService ws=new WebsocketService();
}