服务端:
package com
{
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.events.ServerSocketConnectEvent;
import flash.net.ServerSocket;
import flash.net.Socket;
import flash.utils.ByteArray;
public class AVRSocket
{
private var _serverSocket:ServerSocket = new ServerSocket();
private var _clients:Array=[];//客户端数组
private var _data:String;
private var _localPort:int;
private var _localAddress:String;
private static var _instance:AVRSocket;
public function AVRSocket()
{
}
public static function getInstance():AVRSocket
{
if(!_instance){
_instance = new AVRSocket();
}
return _instance;
}
/**
* 绑定服务端ip和端口
*/
public function bind(host:String = "0.0.0.0", port:int = 0):void
{
try
{
if( _serverSocket.bound )
{
_serverSocket.close();
_serverSocket = new ServerSocket();
}
_serverSocket.bind(port, host);
_serverSocket.addEventListener( ServerSocketConnectEvent.CONNECT, onConnect );
_serverSocket.addEventListener(Event.CLOSE,onClose);
_serverSocket.listen();
_localPort = _serverSocket.localPort;
_localAddress = _serverSocket.localAddress;
trace( "Bound to: " + _serverSocket.localAddress + ":" + _serverSocket.localPort );
}
catch(error:Error)
{
trace("bind error = " + error.message + error.getStackTrace());
}
}
/**
* 客户端成功连接服务器
*/
private function onConnect( event:ServerSocketConnectEvent):void
{
try
{
var clientSocket:Socket = event.socket;
//连接到服务的客户端
_clients.push(clientSocket);
clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData );
clientSocket.addEventListener(Event.CLOSE,onCloseClient);
//建立连接客户端的地址 和 端口
trace( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort);
trace("共" + _clients.length + "个终端已连接到该服务");
}
catch(error:Error)
{
trace("onConnect error = " + error.message + error.getStackTrace());
}
}
private function onClose(e:Event):void
{
trace( "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)
{
_clients.splice(clt,1);
for each(var clt2:Socket in _clients){
clt2.writeUTFBytes("消息:-----");
clt2.flush();
}
trace("\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();
trace( "Received from Client"+ client.remoteAddress + ":" + client.remotePort+"-- " + buffer.toString() );
}
/**
* 服务器向客户端发送信息
*/
public function send(obj:Object):void
{
try
{
if (_clients.length == 0)
{
trace('没有连接');
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 )
{
trace( error.message );
}
}
public function get data():String
{
return _data;
}
public function get localPort():int
{
return _localPort;
}
public function get localAddress():String
{
return _localAddress;
}
}
}
class S{};
终端:
//服务端的端口使用的是自动的生成的空闲端口,所以这里需要服务端告知连接终端端口号
package
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
public class client
{
private var _client:Socket = new Socket();
private static var _instance:client;
public function client()
{
}
public static function getInstance():client
{
if(!_instance){
_instance = new client();
}
return _instance;
}
/**
* 开始连接服务器
*/
public function collect(host:String, port:int):void
{
trace('开始连接服务器!');
trace(host,port);
_client.connect(host, port);
_client.addEventListener(Event.CONNECT, onConnect);//监听连接事件
_client.addEventListener(IOErrorEvent.IO_ERROR,onError);
_client.addEventListener(ProgressEvent.SOCKET_DATA,onSocketData);
_client.addEventListener(Event.CLOSE, closeHandler);// 服务器主动断开连接时调用
}
private function closeHandler(e:Event):void
{
trace("服务端连接断开");
}
/**
*终端主动断开连接
*/
private function closeSocket():void
{
//调用 close() 方法是不能触发 Event.CLOSE 事件的,只有服务端主动断开才可以
_client.close();
}
/**
* 连接服务器成功
*/
private function onConnect(event:Event):void
{
trace("成功连接服务 " +_client.remoteAddress + ":" + _client.remotePort);
}
/**
* 接收到服务器发送的数据
*/
private function onClientSocketData( event:ProgressEvent):void
{
var buffer:ByteArray = new ByteArray();
_client.readBytes( buffer, 0, _client.bytesAvailable );
trace( "Send: " + buffer.toString() );
}
/**
* 接收到服务器发送的数据
*/
private function onSocketData(e:ProgressEvent):void
{
var buffer:String = _client.readUTFBytes(_client.bytesAvailable );
var data:String = buffer.split("\n")[0];
}
/**
* 向服务端发送数据
* @param msg 数据
*/
public function send(msg:String):void
{
try
{
//socket使用 send 和 flush 的时候,如果没有 connect3成功,就会出现异常
if( _client != null && _client.connected )
{
_client.writeUTFBytes(msg);
_client.flush();
}
else
{
trace("No socket connection.");
}
}
catch ( error:Error )
{
trace( error.message );
}
}
private function onError(e:IOErrorEvent):void
{
trace(e.toString());
}
}
}
服务端启动:
var avrSocket:AVRSocket = AVRSocket.getInstance();
avrSocket.bind();
终端启动:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="windowedapplication1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
var c:client;
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
c = client.getInstance();
var host:String = "192.168.20.125";
//服务端的端口使用的是自动的生成的空闲端口,所以这里需要服务端告知连接终端端口号
var port:int = 24516;
c.collect(host, port);
}
protected function button1_clickHandler(event:MouseEvent):void
{
c.send("Hello Word");
}
]]>
</fx:Script>
<mx:Button click="button1_clickHandler(event)"/>
</s:WindowedApplication>