最近一直学习flash as3
今天跟着网上做了一个flash socket 聊天,主要了解下flash如何与java的socket通信。
一段代码CustomSocket.as
package
{
import flash.events.*;
import flash.net.Socket;
import flash.system.*;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
import fl.controls.TextArea;
import fl.core.UIComponent;
/**
* ...
* @author DefaultUser (Tools -> Custom Arguments...)
*/
public class CustomSocket
{
private const CR:int = 13; // Carriage Return (CR)
private const WILL:int = 0xFB; // 251 - WILL (option code)
private const WONT:int = 0xFC; // 252 - WON'T (option code)
private const DO:int = 0xFD; // 253 - DO (option code)
private const DONT:int = 0xFE; // 254 - DON'T (option code)
private const IAC:int = 0xFF; // 255 - Interpret as Command (IAC)
private var serverURL:String;
private var portNumber:int;
private var socket:Socket;
private var ta:TextArea;
private var state:int = 0;
System.useCodePage = false;
public function CustomSocket(server:String, port:int, output:TextArea)
{
serverURL = server;
portNumber = port;
ta = output;
socket = new Socket();
socket.addEventListener(Event.CONNECT, connectHandler);
socket.addEventListener(Event.CLOSE, closeHandler);
socket.addEventListener(ErrorEvent.ERROR, errorHandler);
socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
socket.addEventListener(ProgressEvent.SOCKET_DATA, dataHandler);
Security.loadPolicyFile("http://" + serverURL + ":" + portNumber + "/crossdomain.xml");
try
{
msg("Trying to connect to" + serverURL + ":" + portNumber + "\n");
socket.connect(serverURL,portNumber);
}
catch (error:Error)
{
msg(error.message + "\n");
socket.close();
}
}
public function ioErrorHandler(event:IOErrorEvent):void
{
msg("Unable to connect: socket error.\n");
}
public function writeBytesToSocket(ba:ByteArray):void {
trace(ba);
socket.writeBytes(ba);
socket.flush();
}
private function connectHandler(event:Event):void {
if (socket.connected) {
msg("connected...\n");
} else {
msg("unable to connect\n");
}
}
private function closeHandler(event:Event):void
{
msg("closed...\n");
}
private function errorHandler(event:ErrorEvent):void {
msg(event.text + "\n");
}
private function dataHandler(event:ProgressEvent):void {
var n:int = socket.bytesAvailable;
// Loop through each available byte returned from the socket connection.
while (--n >= 0) {
// Read next available byte.
var b:int = socket.readUnsignedByte();
switch (state) {
case 0:
// If the current byte is the "Interpret as Command" code, set the state to 1.
if (b == IAC) {
state = 1;
// Else, if the byte is not a carriage return, display the character using the msg() method.
} else if (b != CR) {
msg(String.fromCharCode(b));
}
break;
case 1:
// If the current byte is the "DO" code, set the state to 2.
if (b == DO) {
state = 2;
} else {
state = 0;
}
break;
// Blindly reject the option.
case 2:
/*
Write the "Interpret as Command" code, "WONT" code,
and current byte to the socket and send the contents
to the server by calling the flush() method.
*/
socket.writeByte(IAC);
socket.writeByte(WONT);
socket.writeByte(b);
socket.flush();
state = 0;
break;
}
}
}
private function msg(value:String):void {
ta.text += value;
ta.dispatchEvent(new Event(Event.CHANGE));
setTimeout(setScroll, 100);
}
public function setScroll():void {
ta.verticalScrollPosition = ta.maxVerticalScrollPosition;
}
}
}
这个as有的地方没有理解:初始化定义常量时,不知道为什么定义?希望有人能够解释下,小弟不胜感激。
下面还有个Main .as
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.utils.ByteArray;
import CustomSocket;
public class Main extends Sprite
{
private var telnetClient:CustomSocket;
public function Main() {
setupUI();
}
private function connect(e:MouseEvent):void {
//建立socket通信的链接
telnetClient = new CustomSocket(serverName.text, int(portNumber.text), output);
}
private function sendCommand(e:MouseEvent):void {
var ba:ByteArray = new ByteArray();
//将得到的信息写入ba中
ba.writeMultiByte(command.text + "\n", "GBK");
//通过连接写入socket中
telnetClient.writeBytesToSocket(ba);
command.text = "";
}
private function setupUI():void {
loginBtn.addEventListener(MouseEvent.CLICK,connect)
sendBtn.addEventListener(MouseEvent.CLICK,sendCommand);
}
}
}
最后看看java服务器端
代码一:
简单的MyServer .java
package com.cn.socket;
import java.io.*;
import java.net.*;
public class MyServer
{
public static void main (String[] args) throws IOException
{
ServerSocket server=new ServerSocket(4567);
Socket client=server.accept();
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out=new PrintWriter(client.getOutputStream());
while(true)
{
String str=in.readLine();
System.out.println(str);
out.println("你 说: " + str + "\n");
out.flush();
if(str.equals("end"))
break;
}
client.close();
}
}
这个服务器端只能连接一段时间后自动停止。
服务器端代码二:
package com.cn.socket;
import java.io.IOException;
import java.net.*;
import java.util.concurrent.*;
public class MultiThreadServer {
private int port=4567;
private ServerSocket serverSocket;
private ExecutorService executorService;//线程池
private final int POOL_SIZE=10;//单个CPU线程池大小
public MultiThreadServer() throws IOException{
serverSocket=new ServerSocket(port);
//Runtime的availableProcessor()方法返回当前系统的CPU数目.
executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
System.out.println("服务器启动");
}
public void service(){
while(true){
Socket socket=null;
try {
//接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
socket=serverSocket.accept();
executorService.execute(new Handler(socket));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
new MultiThreadServer().service();
}
}
package com.cn.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.*;
public class Handler implements Runnable{
private Socket socket;
public Handler(Socket socket){
this.socket=socket;
}
private PrintWriter getWriter(Socket socket) throws IOException{
OutputStream socketOut=socket.getOutputStream();
return new PrintWriter(socketOut,true);
}
private BufferedReader getReader(Socket socket) throws IOException{
InputStream socketIn=socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public String echo(String msg){
return "echo:"+msg;
}
public void run(){
try {
System.out.println("New connection accepted "+socket.getInetAddress()+":"+socket.getPort());
BufferedReader br=getReader(socket);
PrintWriter pw=getWriter(socket);
String msg=null;
while((msg=br.readLine())!=null){
System.out.println(msg);
pw.println(echo(msg));
if(msg.equals("bye"))
break;
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务器二建立了线程数量,并且可以不断进行端口连接。
这两中服务器选其一就ok。
as3的技术很差,只是为了学习进步。