我可以从一个html页面打开两个WebSocket连接到一个服务器,但两个不同的端口吗?
我在谷歌上搜索过,但找不到任何有用的东西。你还能给我一些web sockets教程的链接吗?这些是我找到的:
http://websocket.org/echo.html http://www.html5rocks.com/en/tutorials/websockets/basics/这样不行吗?
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. js)。. NET, PHP, Node.js等)