as3 与java 都提供了Socket类用于网络通信, 但两者的使用也有较大的不同. 为了方便两者的通信, 我在做了一些实验的基础上, 写下获得的经验,以免忘记.
as3 的socket 读写数据方法常用的有四个: readUTF, writeUTF, readUTFBytes, writeUTFBytesjava 的socket 输入输出流常用BufferedReader 和 DataOutputStream 包装, 以提高读写效率
如:
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
DataOutputStream writer = new DataOutputStream(socket.getOutputStream());
as3 方写数据时用writeUTFBytes 方法, 此时java 方读数据用reader.readLine() 阻塞式方法.
as3 方写数据时用writeUTF方法, 此时java 方应改用DataInputStream 类包装输入流, 因为BufferedReader 不提供读取UTF数据的方法.
java 方写数据时用writeUTF方法, 此时as3 方读数据用readUTF方法, 但此种模式有个弊端, 就是如果java方连续调用了n(n >= 2)次writeUTF方法,而as3方因来不及读取, 则最后只是第一次写入的数据被读取.
java 方写数据时用writeBytes, 此时as3 方读数据用readUTFBytes方法读取数据, 可以这样读取: msg = socket.readUTFBytes(socket.bytesAvailable).
一个简单的例子:
// as3 写的客户端
package test
{
import flash.display.MovieClip;
import flash.net.Socket;
import flash.events.ProgressEvent;
import flash.events.IOErrorEvent;
public class TestSocket extends MovieClip
{
private var socket:Socket;
private var msg:String;
public function TestSocket() {
init();
}
private function init() {
socket = new Socket("localhost", 60000);
socket.addEventListener(ProgressEvent.SOCKET_DATA, readMsg);
socket.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
}
private function readMsg(e:ProgressEvent) {
msg = socket.readUTF();
trace("message:" + msg);
}
private function errorHandler(e:IOErrorEvent) {
trace(e.toString);
}
}
}
//java 写的服务器端
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TestSocket {
private ServerSocket socketServer;
private Socket client;
private DataOutputStream writer;
private BufferedReader reader;
public static void main(String[] args) {
int socketPort = 60000;
TestSocket test1 = new TestSocket(socketPort);
}
public TestSocket(int socketPort) {
try {
socketServer = new ServerSocket(socketPort);
System.out.println("server is setted up");
while (true) {
client = socketServer.accept();
//wrap input and output stream
writer = new DataOutputStream(client.getOutputStream());
reader = new BufferedReader(newInputStreamReader(client.getInputStream()));
//send message to client
writer.writeUTF("hello client");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}