Socket服务器

package com.controls.socket
{
import com.models.events.AppEvent;
import com.models.events.AppEventDispatcher;
import com.models.util.Config; import flash.events.Event;
import flash.events.ProgressEvent;
import flash.events.ServerSocketConnectEvent;
import flash.net.ServerSocket;
import flash.net.Socket;
import flash.utils.ByteArray; /**
* @author Frost.Yen
* @email 871979853@qq.com
* @build 2016-8-8 下午8:35:00
*/
public class SocketServer
{
private var _serverSocket:ServerSocket = new ServerSocket();
private var _clients:Array=[];//客户端数组
private var _data:String;
private static var _instance:SocketServer;
public function SocketServer(s:S)
{
}
public static function getInstance():SocketServer
{
if(!_instance){
_instance = new SocketServer(new S());
}
return _instance;
}
/**
* 绑定服务端ip和端口
* @localPort 端口
* @localAddress ip地址
*/
public function bind(localPort:int,localAddress:String):void
{
if( _serverSocket.bound )
{
_serverSocket.close();
_serverSocket = new ServerSocket();
}
_serverSocket.bind( localPort, localAddress);
_serverSocket.addEventListener( ServerSocketConnectEvent.CONNECT, onConnect );
_serverSocket.addEventListener(Event.CLOSE,onClose);
_serverSocket.listen();
log( "Bound to: " + _serverSocket.localAddress + ":" + _serverSocket.localPort );
}
/**
* 客户端成功连接服务器
*/
private function onConnect( event:ServerSocketConnectEvent):void
{
var clientSocket:Socket = event.socket;
clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData );
_clients.push(clientSocket);
       clientSocket.addEventListener(Event.CLOSE,onCloseClient);
log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
//trace(_clients.length,"_clients.length",Config.clientNum,"Config.clientNum");
if(_clients.length == Config.clientNum){
log("所有客户端连接成功,共"+_clients.length+"台");
AppEventDispatcher.getInstance().dispatchEvent(new AppEvent(AppEvent.CONNECT_SUCCEED));
}
} private function onClose(e:Event):void
{
log( "Connection Faild " );
}
     private function onCloseClient(e:Event):void
{
for (var clt:int=0;clt<_clients.length;clt++){
if(_clients[clt].remoteAddress==e.target.remoteAddress&&_clients[clt].remotePort==e.target.remotePort){
var msgObj:Object=_clientDic[_clients[clt].remoteAddress+_clients[clt].remotePort];
delete _clientDic[_clients[clt].remoteAddress+_clients[clt].remotePort];
_clients.splice(clt,1);
if(msgObj){
for each(var clt2:Socket in _clients){
clt2.writeUTFBytes("消息:-----");
clt2.flush();
}
}
msgObj=null; log("\n"+ e.target.remoteAddress+":"+e.target.remotePort+ "断开");
}
} }
/**
* 服务端接收客户端发送的信息
*/
private function onClientSocketData( event:ProgressEvent ):void
{
var buffer:ByteArray = new ByteArray();
var client:Socket = event.currentTarget as Socket;
client.readBytes( buffer, 0, client.bytesAvailable );
_data = buffer.toString();
AppEventDispatcher.getInstance().dispatchEvent(new AppEvent(AppEvent.CLIENT_DATA,buffer));
log( "Received from Client"+ client.remoteAddress + ":" + client.remotePort+"-- " + buffer.toString() );
}
/**
* 服务器向客户端发送信息
*/
public function send(obj:Object):void
{
try
{
if (_clients.length == 0)
{
log('没有连接');
return;
}
for (var i:int = 0; i < _clients.length; i++)
{
var item:Socket = _clients[i] as Socket;
if (!item) continue;
item.writeUTFBytes(JSON.stringify(obj)+"\n");
item.flush();
}
}catch ( error:Error )
{
log( error.message );
}
}
public function log(message:String):void
{
//trace(message);
} public function get data():String
{
return _data;
} }
}
class S{};

Socket客户端

package com.controls
{
import com.models.events.AppEvent;
import com.models.events.AppEventDispatcher; import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.Socket;
import flash.utils.ByteArray; /**
* @author Frost.Yen
* @email 871979853@qq.com
* @build 2016-8-9 下午5:55:19
*/
public class SocketClient
{
private var _client:Socket = new Socket();
private static var _instance:SocketClient;
public function SocketClient(s:S)
{
}
public static function getInstance():SocketClient
{
if(!_instance){
_instance = new SocketClient(new S());
}
return _instance;
}
/**
* 开始连接服务器
* @param host ip地址
* @param port 端口
*/
public function collect(host:String,port:int):void
{
log('开始连接服务器!');
trace(host,port);
_client.connect(host, port);
_client.addEventListener(Event.CONNECT, onConnect);//监听连接事件
_client.addEventListener(IOErrorEvent.IO_ERROR,onError);
_client.addEventListener(ProgressEvent.SOCKET_DATA,onSocketData);
}
/**
* 连接服务器成功
*/
private function onConnect( event:Event ):void
{
log('成功连接服务器!');
log( "Connection from " + _client.remoteAddress + ":" + _client.remotePort );
}
private function onClientSocketData( event:ProgressEvent):void
{
var buffer:ByteArray = new ByteArray();
_client.readBytes( buffer, 0, _client.bytesAvailable );
log( "Send: " + buffer.toString() );
}
/**
* 接收到服务器发送的数据
*/
private function onSocketData(e:ProgressEvent):void
{
var buffer:String = _client.readUTFBytes(_client.bytesAvailable );
var data:String = buffer.split("\n")[0];
AppEventDispatcher.getInstance().dispatchEvent(new AppEvent(AppEvent.SERVER_DATA,data));
log( "Received from Server:" + buffer );
}
/**
* 向服务端发送数据
* @param msg 数据
*/
private function send(msg:String):void
{
try
{
if( _client != null && _client.connected )
{
_client.writeUTFBytes(msg);
_client.flush();
//log( "Sent message to " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
}
else log("No socket connection.");
}
catch ( error:Error )
{
log( error.message );
}
}
private function onError(e:IOErrorEvent):void
{
log(e.toString());
}
public function log(message:String):void
{
//trace(message);
} }
}
class S{};

代码中的导入的类:

import com.models.events.AppEvent;
import com.models.events.AppEventDispatcher;

是用于接收到数据后向外派发事件时所用,可自行处理。

[ActionScript 3.0] AS3.0 简单封装Socket的通信的更多相关文章

  1. [ActionScript 3.0] AS3.0和AS2.0的相互通信

    AS3和AS2之间的通信,最好的方式可能就是LocalConnection了. AS2向AS3发送数据,即AS2调用AS3的函数: as2.0代码(按钮上写的发送信息代码): on (release) ...

  2. [ActionScript 3.0] AS3.0 让一个视频无缝循环播放的一个偏方

    一个视频要循环播放,通常的办法都是播放完后再重新播放,但是不可避免的播放结束和重新开始播放这个时间点上会有停顿,如何解决这个问题,说个偏方吧! package com.views { import f ...

  3. [ActionScript 3.0] AS3.0 下雨及涟漪效果

    帧代码: stage.frameRate = 80; function init(x1:Number,y1:Number) { var mc:MovieClip=new MovieClip(); ad ...

  4. [ActionScript 3.0] AS3.0 Socket通信实例

    以下类是充当Socket服务器的例子 package { import flash.display.Sprite; import flash.events.Event; import flash.ev ...

  5. [ActionScript 3.0] AS3.0 本机鼠标指针

    Flash Player 10.2添加了内置的本机鼠标指针(native mouse cursor)支持,虽然在之前的版本里我们可以侦听MouseEvent事件来模拟鼠标指针,但是在有了原生的本机鼠标 ...

  6. [ActionScript 3.0] AS3.0 动态加载显示内容

    可以将下列任何外部显示资源加载到 ActionScript 3.0 应用程序中: 在 ActionScript 3.0 中创作的 SWF 文件 — 此文件可以是 Sprite.MovieClip 或扩 ...

  7. [ActionScript 3.0] AS3.0 涂鸦及擦除功能,撤销重做步骤记录实例

    package { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.BlendMo ...

  8. [ActionScript 3.0] AS3.0 对象在矩形范围随机运动

    package com.views { import flash.display.Bitmap; import flash.display.MovieClip; import flash.displa ...

  9. [ActionScript 3.0] AS3.0 将图像的Alpha通道转换为黑白图像(分离ARGB方式)

    import flash.display.BitmapData; import flash.display.Bitmap; /** * 将图像的Alpha通道转换为黑白图像(分离ARGB方式) */ ...

随机推荐

  1. Android APK反编译就这么简单 详解(附图)

    在学习Android开发的过程你,你往往会去借鉴别人的应用是怎么开发的,那些漂亮的动画和精致的布局可能会让你爱不释手,作为一个开发者,你可能会很想知道这些效果界面是怎么去实现的,这时,你便可以对改应用 ...

  2. Java 导出EXCEL

    1.Apache POI简介 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能. .NET的开发人员则 ...

  3. HTML中head里的内容经浏览器解析后全到body里

    我从linux服务器nginx上把一个网站迁移到windows的IIS上数据什么的都么有问题,配置好rewrite以后,访问网站,发现样式变动了,网站上方空出了一块我用chrome浏览器的审查元素一看 ...

  4. 【转】Mybatis 3.1中 Mapper XML 文件 的学习详解

    MyBatis 真正的力量是在映射语句中.这里是奇迹发生的地方.对于所有的力量,SQL 映射的 XML 文件是相当的简单.当然如果你将它们和对等功能的 JDBC 代码来比较,你会发现映射文件节省了大约 ...

  5. SparkSQL之旅

    1.准备数据employee.txt ,Gong Shaocheng, ,Li Dachao, ,Qiu Xin, ,Cheng Jiangzhong, ,Wo Binggang, 将数据放入hdfs ...

  6. hdu 1057 (simulation, use sentinel to avoid boudary testing, use swap trick to avoid extra copy.) 分类: hdoj 2015-06-19 11:58 25人阅读 评论(0) 收藏

    use sentinel to avoid boudary testing, use swap trick to avoid extra copy. original version #include ...

  7. 说一说vector<bool>

    vector<T>标准库模版类应该是绝大多数c++程序员使用频率比较高的一个类了.不过vector<bool>也许就不那么被程序员所了解.关于vector<bool> ...

  8. Unity3D和OGRE资源管理机制

    转自:http://www.tuicool.com/articles/QbMjUn 游戏中通常有大量资源,如网格.材质.纹理.动画.着色器程序和音乐等,游戏引擎作为做游戏的工具,自然要提供良好的资源管 ...

  9. HDU 2254

    http://acm.hdu.edu.cn/showproblem.php?pid=2254 矩阵乘法两个经典问题的综合题,还要离散化和处理边界,好题啊好题 题意容易理解错,每一天是独立的,所以根据加 ...

  10. Activity 属性设置大全

    activity属性设置大全 android:allowTaskReparenting=["true"|"false"] 是否允许activity更换从属的任务 ...