【发布时间】:2011-11-02 14:58:58
【问题描述】:
我可以打开两个 WebSocket 连接到一台服务器,但从一个 html 页面打开两个不同的端口。
我在谷歌上搜索过,但找不到任何有用的东西。您还可以给我一些 Web 套接字教程的链接吗?这些是我找到的:
【问题讨论】:
标签: javascript html websocket
我可以打开两个 WebSocket 连接到一台服务器,但从一个 html 页面打开两个不同的端口。
我在谷歌上搜索过,但找不到任何有用的东西。您还可以给我一些 Web 套接字教程的链接吗?这些是我找到的:
【问题讨论】:
标签: javascript html websocket
这样不行吗?
var socket1 = new WebSocket('ws://localhost:1001');
var socket2 = new WebSocket('ws://localhost:1002');
至于你的服务器如何处理它,很大程度上取决于你的服务器端技术。
对于教程,WebSockets 的客户端方面非常简单,就是这样:
var socket;
// Firefox uses a vendor prefix
if (typeof(MozWebSocket) != 'undefined') {
socket = new MozWebSocket('ws://localhost');
}
else if (typeof(WebSocket) != 'undefined') {
socket = new WebSocket('ws://localhost');
}
if (socket != null) {
socket.onmessage = function(event) {
// fired when a message is received from the server
alert(event.data);
};
socket.onclose = function() {
// fired when the socket gets closed
};
socket.onerror = function(event) {
// fired when there's been a socket error
};
socket.onopen = function() {
// fired when a socket connection is established with the server,
// Note: we can now send messages at this point
// sending a simple string to the server
socket.send('Hello world');
// sending a more complex object to the server
var command = {
action: 'Message',
time: new Date().toString(),
message: 'Hello world'
};
socket.send(JSON.stringify(command));
};
}
else {
alert('WebSockets are not supported by your browser');
}
如何处理传入 WebSocket 连接的服务器端方面要复杂得多,并且取决于您的服务器端技术(ASP.NET、PHP、Node.js 等)。
【讨论】: