分类: Java
2010-04-15 14:54:22
今天突发奇想,网页的flash游戏都是怎么做的,所以看了看flash和java的socket通信,结果还真好用。。。太邪恶了
新建flash文件:SocketExample.fla
添加按钮:btnSend
修改文档类为:SocketExample
新建AS3文件:SocketExample.as
package { import flash.display.Sprite; import flash.events.*; import flash.net.Socket; public class SocketExample extends Sprite { private var socket:Socket; public function SocketExample( ) { socket = new Socket( ); // Add an event listener to be notified when the connection // is made socket.addEventListener( Event.CONNECT, onConnect ); // Listen for when data is received from the socket server socket.addEventListener( ProgressEvent.SOCKET_DATA, onSocketData ); //var btnSend:Button = new Button(); btnSend.label = "Send Data"; btnSend.emphasized = true; btnSend.width = 150; btnSend.move(20, 20); addChild(btnSend); btnSend.addEventListener(MouseEvent.CLICK, sendData); } private function sendData( event:Event ) { if (!socket.connected) { // Connect to the server socket.connect( "192.168.2.103", 5678 ); } trace("send..."); socket.writeUTFBytes("example\n"); socket.flush(); } private function onConnect( event:Event ):void { trace( "The socket is now connected..." ); } private function onSocketData( eventrogressEvent ):void { trace( "Socket received " + socket.bytesAvailable + " byte(s) of data:" ); trace(socket.readMultiByte(socket.bytesAvailable, "UTF-8")); } } }
Java服务器端:
MyServer.java
import java.io.*; import java.net.*; public class MyServer { public static void main(String[] args) throws IOException{ ServerSocket server=new ServerSocket(5678); while (true) { 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("has receive...."); out.flush(); if("end".equals(str)) break; //} client.close(); } } }
客户端控制台输出:
send...
The socket is now connected...
Socket received 17 byte(s) of data:
has receive....
我们在使用ActionScript3.0进行Socket编程的时候需要关注下面的问题,我们将在今后的学习中逐个对下面的问题进行讨论,并尽量逐渐的改进我们的程序.
1.与Socket服务器建立连接.
2.向Socket服务器发送数据.
3.从Socket服务器读数据.
4.同Socket服务器进行握手,并确定收到了什么样的数据和如何处理这些数据.
5.与Socket服务器断开,或者当服务器想与你断开的时候发消息给你.
6.处理使用Sockets时候引发的错误.
1.与Socket服务器建立连接.
3.从Socket服务器读数据
方法:返回值类型 | 描述 | 字节数 |
readBoolean( ):Boolean | 从Socket读取一个Boolean值. | 1 |
readByte( ):int | 从Socket读取一个byte值. | 1 |
readDouble( ):Number | 从Socket读取一个IEEE 754双精度浮点数. | 8 |
readFloat( ):Number | 从Socket读取一个IEEE 754单精度浮点数. | 4 |
readInt( ):int | 从Socket读取一个有符号32-bit整数值. | 4 |
readObject( ):* | 从Socket读取一个AMF-encoded对象. | n |
readShort( ):int | 从Socket读取一个有符号16-bit整数值. | 2 |
readUnsignedByte( ):uint | 从Socket读取一个无符号字节. | 1 |
readUnsignedInt( ):uint | 从Socket读取一个无符号32-bit整数 | 4 |
readUnsignedShort( ):uint | 从Socket读取一个无符号16-bit整数. | 2 |
readUTF( ):String | 从Socket读取一个一个UTF8字符串. | n |
4.同Socket服务器进行握手
5.与Socket服务器断开
6.处理使用Sockets时候引发的错误