Flex与Java通信的方式有很多种,比较常用的有以下方式:
WebService:一种跨语言的在线服务,只要用特定语言写好并部署到服务器,其它语言就可以调用
HttpService:通过http请求的形式访问服务器
RmoteObject:通过AMF协议,以二进制的形式交互数据
Socket:套接字协议,服务器和客户端以IO的形式交互数据
上面几种各有个的优势:WebService常用于跨语言调用,不过解析协议需要花不少时间,运行速度不快;HttpService类似于Ajax;通常RmoteObject是最受欢迎的,因为它的运行效率快,数据解析方便。
下面来看看几种方式
Http请求
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
PrintWriter w = response.getWriter();
w.write("hello ");
w.close();
}
public function httpService():void{
var http:HTTPService = new HTTPService();
http.url = "http://localhost:8888/JavaToFlex/HelloHttp?name="+input.text;
http.send();
http.addEventListener(ResultEvent.RESULT,function
callback(e:ResultEvent):void{
showMessage.text = e.result.toString();
});
}
Socket
package loowj.web;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public ServerSocket server;
public static void main(String[] args) {
Server s = new Server();
try {
//在端口719建立一个服务器套接字对象
s.server=new ServerSocket(719);
System.out.println("服务端等待");
while(true){
System.out.println("等待客户机");
Socket newSocket = s.server.accept();
System.out.println("已与客户机连接");
}
} catch (IOException e) {
e.printStackTrace();
if(s.server!=null)
try {
s.server.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
private var so:Socket = new Socket();
public function soket():void{
so.connect("localhost",719); //连接服务器
so.addEventListener(Event.CONNECT,function(e:Event):void{//监听是否连接
showMessage.text = "soket 连接";
});
so.addEventListener(Event.CLOSE,function(e:Event):void{ //监听连接关闭
showMessage.text = "soket 连接关闭";
});
}
RmoteObject
http://my.oschina.net/wjgood/blog/33510