flash代码:
package
{
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.system.*;
import flash.text.*;
import flash.utils.*;
/*
*
*/
public class Client extends Sprite {
public function Client():void {
var socket:Socket = new Socket();
socket.addEventListener(Event.CONNECT,onEvent);//侦听连接事件
socket.addEventListener(Event.CLOSE,onEvent);//侦听关闭事件
socket.addEventListener(ProgressEvent.SOCKET_DATA,onEvent);//侦听数据收到事件
socket.connect('127.0.0.1',3944);//连接服务端
}
public function onEvent(e:Event):void {
var socket:Socket = e.target as Socket;
switch(e.type){
case Event.CONNECT:
trace('已连接成功');
socket.writeUTFBytes('我是来自客户端的消息');//把字符串按照utf-8的编码发出去
break;
case Event.CLOSE:
trace('服务器关闭!');
socket.close();
break;
case ProgressEvent.SOCKET_DATA:
trace('收到数据,长度'+socket.bytesAvailable);
read(socket);
break;
}
}
public function read(socket:Socket):void {
var ba:ByteArray = new ByteArray();//缓冲区
socket.readBytes(ba,0,socket.bytesAvailable);//按收到的数据长度来读
var val:String = ba.readUTFBytes(ba.length);//安装utf-8的编码解析二进制
trace(val);
}
}
}
服务端代码:
var XML =
'<?xml version="1.0"?>' +
'<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">' +
'<cross-domain-policy>' +
'<allow-access-from domain="*" to-ports="*" />' +
'</cross-domain-policy>'
var net = require('net'),
http = require("http"),
fs = require("fs"),
path = require("path"),
url = require("url");
var index = 0;
var server = net.createServer(
function(socket){
index++;
new Client(index,socket);
});
server.listen(3944, '127.0.0.1');
console.log('服务端已开启...');
function Client(index,socket) {
var myIndex = index;
socket.setTimeout(1500, function() {
console.log(socket.remoteAddress + ' 超时');
socket.destroy();
});
socket.on('data', function(data) {
if(data.toString()=='<policy-file-request/>\0'){
socket.write('你好,第'+myIndex+'号客户端。我是服务端','utf-8');
socket.write(XML);
console.log('相等');
console.log(data.toString());
socket.end();
}
});
}
8 回复
重复读了3次标题,惭愧啊,以我小学语文没毕业的水平,只能看懂问题是关于flash封装的跨域要引用策略文件
,但是具体是什么,flash客户端发送不出?服务端接受不到?访问拒绝?flash不能解析策略文件?无解。楼下能看明白的,请告之并BS我吧。
呃,既然回帖姑且猜猜看看吧。请求既然以0结束,回复不也应该以0结束吗。
if(data.toString()=='<policy-file-request/>\0'){
socket.write(XML+'\0');
console.log('相等');
console.log(data.toString());
socket.end();
}
@jiyinyiyong 搞定了
socket.on('data', function(data) {
if(data.toString()=='<policy-file-request/>\0'){
socket.end(XML);
console.log('客户端flash已与服务器建立连接,可以正常传输数据了!');
}else{
console.log(data.toString());
socket.write(data.toString());
}
});
加了else,在else发送就行了