AS3 XMLSocket从已启动的所有客户端发送数据,但仅由最后连接的客户端收到数据。
我有Flash网络客户端,如果您打开应用程序的2个或更多选项卡,每个客户端都会将数据发送到套接字服务器,但只有最后连接的客户端才能获取所有数据。这是链接http://151.248.124.213/
。它现在有聊天相似的界面,绿色按钮是SEND按钮。当您使用鼠标进入舞台时,应用程序将连接。当消息Connected出现在屏幕上时,应用程序已连接。要测试http://151.248.124.213/
,只需打开2个或更多标签。
这是AS3代码:
Security.loadPolicyFile("xmlsocket://151.248.124.213:3843");
var socket:XMLSocket;
stage.addEventListener(MouseEvent.CLICK, doConnect);
function doConnect(evt:Event):void
{
stage.removeEventListener(MouseEvent.CLICK, doConnect);
socket = new XMLSocket("151.248.124.213", 3000);
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
}
function onConnect(evt:Event):void
{
trace("Connected");
output_txt.text = "Connected\n";
socket.removeEventListener(Event.CONNECT, onConnect);
socket.removeEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(DataEvent.DATA, onDataReceived);
socket.addEventListener(Event.CLOSE, onSocketClose);
}
function onSocketClose(evt:Event):void
{
trace("Connection Closed");
socket.removeEventListener(Event.CLOSE, onSocketClose);
socket.removeEventListener(DataEvent.DATA, onDataReceived);
}
function onError(evt:IOErrorEvent):void
{
trace("Connect failed");
socket.removeEventListener(Event.CONNECT, onConnect);
socket.removeEventListener(IOErrorEvent.IO_ERROR, onError);
}
function onDataReceived(evt:DataEvent):void
{
try {
trace( "From Server:", evt.data );
var msg = evt.data;
output_txt.text += msg + "\n";
}
catch (e:Error) {
trace('error');
}
}
send_btn.addEventListener(MouseEvent.CLICK, send_btn_clicked);
function send_btn_clicked(evt:MouseEvent):void
{
var msg = input_txt.text;
socket.send(msg);
input_txt.text = "";
}
这是服务器代码:
var express = require('express');
var app = express.createServer();
app.configure(function () {
app.use(express.static(__dirname));
})
app.listen(80);
var net = require('net');
var mySocket;
var server = net.createServer(function(socket) {
mySocket = socket;
mySocket.on("connect", onConnect);
mySocket.on("data", onData);
});
server.listen(3000);
function onConnect()
{
console.log("Connected to Flash");
}
function onData(d)
{
if(d == "exit\0")
{
console.log("exit");
mySocket.end();
server.close();
}
else
{
console.log("From Flash = " + d);
mySocket.write(d, 'utf8');
}
}