两个html页面公用一个socket,javascript-HTML5从一个html页面打开两个Web套接字

这行不通吗?

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等).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值