博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(转)利用AIR的ServerSocket类让 AIR 做socket服务器
阅读量:5840 次
发布时间:2019-06-18

本文共 9979 字,大约阅读时间需要 33 分钟。

自:http://luoke920.iteye.com/blog/1161549

新的air sdk 新增了 ServerSocket类, 利用它我们做一些简单的局域网应用,比如小型的办公聊天软件,以及一些基于socket的服务应用.这样as程序员可以自己搞定服务器端,不在去求于 java程序员.在一下大型应用还没有尝试过.期待有人能做一下大型应用的尝试.小型的办公应用足够能满足了.

首先看服务器端代码:

 ACTIONSCRIPT
package{
import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.events.ProgressEvent; import flash.events.ServerSocketConnectEvent; import flash.net.ServerSocket; import flash.net.Socket; import flash.text.TextField; import flash.text.TextFieldType; import flash.utils.ByteArray;  public class Main extends Sprite {
private var serverSocket:ServerSocket = new ServerSocket(); private var clientSocket:Socket;  private var localIP:TextField; private var localPort:TextField; private var logField:TextField; private var message:TextField; private var _clients:Array = [];  public function Main() {
setupUI(); }  //当客户端成功连接服务端 private function onConnect( event:ServerSocketConnectEvent):void {
clientSocket = event.socket; clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData ); _clients.push(clientSocket); log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort ); }  //当有数据通信时 private function onClientSocketData( event:ProgressEvent ):void {
var buffer:ByteArray = new ByteArray(); clientSocket.readBytes( buffer, 0, clientSocket.bytesAvailable ); log( "Received: " + buffer.toString() );  for (var i:int = 0; i < _clients.length; i++) {
var item:Socket = _clients[i] as Socket; if (!item) continue; item.writeObject(buffer.toString()); item.flush(); }   } //绑定服务器ip 开始监听端口 private function bind( event:Event ):void {
if( serverSocket.bound ) {
serverSocket.close(); serverSocket = new ServerSocket();  } serverSocket.bind( parseInt( localPort.text ), localIP.text ); serverSocket.addEventListener( ServerSocketConnectEvent.CONNECT, onConnect ); serverSocket.listen(); log( "Bound to: " + serverSocket.localAddress + ":" + serverSocket.localPort ); }  //服务器端向所有客户端发送数据 private function send( event:Event ):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.writeObject(message.text); item.flush(); }  /*if( clientSocket != null && clientSocket.connected ) { clientSocket.writeUTFBytes( message.text ); clientSocket.flush(); log( "Sent message to " + clientSocket.remoteAddress + ":" + clientSocket.remotePort ); } else log("No socket connection.");*/ } catch ( error:Error ) {
log( error.message ); } }  // 输出日志 private function log( text:String ):void {
logField.appendText( text + "\n" ); logField.scrollV = logField.maxScrollV; trace( text ); }  //设置皮肤 private function setupUI():void {
localIP = createTextField( 10, 10, "Local IP", "0.0.0.0"); localPort = createTextField( 10, 35, "Local port", "0" ); createTextButton( 170, 60, "Bind", bind ); message = createTextField( 10, 85, "Message", "Lucy can't drink milk." ); createTextButton( 170, 110, "Send", send ); logField = createTextField( 10, 135, "Log", "", false, 200 )  this.stage.nativeWindow.activate(); }  private function createTextField( x:int, y:int, label:String, defaultValue:String = '', editable:Boolean = true, height:int = 20 ):TextField {
var labelField:TextField = new TextField(); labelField.text = label; labelField.type = TextFieldType.DYNAMIC; labelField.width = 100; labelField.x = x; labelField.y = y;  var input:TextField = new TextField(); input.text = defaultValue; input.type = TextFieldType.INPUT; input.border = editable; input.selectable = editable; input.width = 280; input.height = height; input.x = x + labelField.width; input.y = y;  this.addChild( labelField ); this.addChild( input );  return input; }  private function createTextButton( x:int, y:int, label:String, clickHandler:Function ):TextField {
var button:TextField = new TextField(); button.htmlText = "" + label + ""; button.type = TextFieldType.DYNAMIC; button.selectable = false; button.width = 180; button.x = x; button.y = y; button.addEventListener( MouseEvent.CLICK, clickHandler );  this.addChild( button ); return button; } }}

客户端代码,主要就是连接服务器端:

 ACTIONSCRIPT
package{
import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.events.ProgressEvent; import flash.events.ServerSocketConnectEvent; import flash.net.ServerSocket; import flash.net.Socket; import flash.text.TextField; import flash.text.TextFieldType; import flash.utils.ByteArray;  public class MainClient extends Sprite {
private var serverSocket:ServerSocket = new ServerSocket(); private var clientSocket:Socket;  private var localIP:TextField; private var localPort:TextField; private var logField:TextField; private var message:TextField;  private var _clients:Array = [];  public function MainClient() {
setupUI(); }  private function onConnect( event:Event ):void {
log('成功连接服务器!'); //trace('成功连接服务器!!!!'); //clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData ); log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort ); }  private function onClientSocketData( event:ProgressEvent ):void {
var buffer:ByteArray = new ByteArray(); clientSocket.readBytes( buffer, 0, clientSocket.bytesAvailable ); log( "Received: " + buffer.toString() ); }  public function bind(host:String = "localhost", port:Number = 9080):void {
log('开始连接服务器!'); clientSocket = new Socket( localIP.text, parseInt( localPort.text )); clientSocket.addEventListener(Event.CONNECT, onConnect);//监听连接事件  }  //向服务器发送数据 private function send( event:Event ):void {
try {
if( clientSocket != null && clientSocket.connected ) {
clientSocket.writeUTFBytes( message.text ); clientSocket.flush(); //log( "Sent message to " + clientSocket.remoteAddress + ":" + clientSocket.remotePort ); } else log("No socket connection."); } catch ( error:Error ) {
log( error.message ); } }  private function log( text:String ):void {
logField.appendText( text + "\n" ); logField.scrollV = logField.maxScrollV; trace( text ); }  private function setupUI():void {
localIP = createTextField( 10, 10, "Local IP", "0.0.0.0"); localIP.text = 'localhost'; localPort = createTextField( 10, 35, "Local port", "0" ); createTextButton( 170, 60, "Bind", bind ); message = createTextField( 10, 85, "Message", "Lucy can't drink milk." ); createTextButton( 170, 110, "Send", send ); logField = createTextField( 10, 135, "Log", "", false, 200 )  this.stage.nativeWindow.activate(); }  private function createTextField( x:int, y:int, label:String, defaultValue:String = '', editable:Boolean = true, height:int = 20 ):TextField {
var labelField:TextField = new TextField(); labelField.text = label; labelField.type = TextFieldType.DYNAMIC; labelField.width = 100; labelField.x = x; labelField.y = y;  var input:TextField = new TextField(); input.text = defaultValue; input.type = TextFieldType.INPUT; input.border = editable; input.selectable = editable; input.width = 280; input.height = height; input.x = x + labelField.width; input.y = y;  this.addChild( labelField ); this.addChild( input );  return input; }  private function createTextButton( x:int, y:int, label:String, clickHandler:Function ):TextField {
var button:TextField = new TextField(); button.htmlText = "" + label + ""; button.type = TextFieldType.DYNAMIC; button.selectable = false; button.width = 180; button.x = x; button.y = y; button.addEventListener( MouseEvent.CLICK, clickHandler );  this.addChild( button ); return button; } }}

整体实现起来比较简单, 服务器端可以做分发. 如果做个聊天室也非常容易. 期待air的效率能再提高一些.

转载地址:http://wtvcx.baihongyu.com/

你可能感兴趣的文章
SCCM2012 R2实战系列之十:解决WDS服务无法启动问题(错误1067:进程意外终止)...
查看>>
怎么防止重复发送Ajax
查看>>
ubuntu 下安装 mysql
查看>>
关于k-means聚类算法的matlab实现
查看>>
Git分支2
查看>>
一键安装Gitlab后的备份、迁移与恢复
查看>>
因为本人工作繁忙,精力有限,本博客停止更新。有兴趣的博友可以关注我在CSDN上的主博客...
查看>>
SQL server查看触发器是否被禁用
查看>>
[C++基础]在构造函数内部调用构造函数
查看>>
跟随我在oracle学习php(8)
查看>>
Spring 3.1.0 Hibernate 3.0 Eclipse Spring WEB例子
查看>>
UVA-10212 The Last Non-zero Digit. 分解质因子+容斥定理
查看>>
求两个集合的交集,并集,差集
查看>>
Kotlin的语法糖(一)基础篇
查看>>
OkHttp源码分析
查看>>
让你的app体验更丝滑的11种方法!冲击手机应用榜单Top3指日可待
查看>>
windows kernel exploitation基础教程
查看>>
NS_OPTIONS枚举的用法
查看>>
java9系列(九)Make G1 the Default Garbage Collector
查看>>
QAQ高精度模板笔记√
查看>>