`
海盗大哥
  • 浏览: 63684 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

flex与JAVA的SOCKET通信 之石头剪刀布 研究flex三天的结果 附上源代码

阅读更多
开始之前建议先看看这边文章(ActionScript3.0 Socket编程):
http://blog.chinaunix.net/u2/60074/showart_508964.html
对于开发环境的配置建议参考这边文章
http://www.yeeach.com/2009/07/21/%E4%BD%BF%E7%94%A8blazeds%E5%AE%9E%E7%8E%B0java%E5%92%8Cflex%E9%80%9A%E4%BF%A1%E4%B9%8Bhello-world/

<嘿嘿 大部分都是抄的不过能看的懂就OK了>
客服端代码

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" fontSize="12" creationComplete="initApp()">
	
	<mx:Script>
	<![CDATA[
	import flash.net.Socket;
	import mx.controls.Alert;
	import flash.utils.ByteArray;
	
	private var socket:Socket = new Socket();//定义Socket,准备好情书的信封
	//初始化程序
	internal function initApp():void
	{
		socket.addEventListener(Event.CONNECT,funConnect); //监听是否连接
		socket.addEventListener(Event.CLOSE,funClose); //监听连接关闭
		socket.addEventListener(ProgressEvent.SOCKET_DATA,funSocket); //监听输入流
		socket.connect("localhost",1024); //连接服务器
	}
	
	internal function funSocket(event:ProgressEvent) {
		var srt:String = socket.readUTF();
		loveText.text = loveText.text + "\n 机器人说:" + srt+"\n";
	}
	
	internal function funConnect(event:Event):void
	{
		loveText.text+="\n连接已建立 \n";
	}
	internal function funClose(event:Event):void
	{
		loveText.text+="\n连接已关闭 \n";
	}
	
	internal function sendMessage(msg:String):void//发送数据对应按钮click事件
	{
		var message:ByteArray=new ByteArray();//新建一个ByteArray存放数据
		loveText.text+=msg+"\r\n";//在客户端屏幕上输出发送的内容
		message.writeUTFBytes(msg +"\r\n");//写入数据,writeUTFBytes方法,以utf-8格式传数据避免中文乱码
		socket.writeBytes(message); //写入Socket的缓冲区
		socket.flush();//调用flush方法发送信息
		loveInput.text="";//清空发言框
	}
	]]>
	</mx:Script>
	
	<mx:TextArea x="10" y="10" width="703" height="263" id="loveText"/>
	<mx:TextInput x="10" y="297" width="605" id="loveInput"/>
	<mx:Button x="648" y="297" label="回复的内容" id="sendBtn" click="sendMessage(loveInput.text)"/>
	
</mx:Application>


服务器端:
	private static Test test;
	private BufferedReader reader;// 负责输入
	private Random ran = new Random(); //用于随机数
	
	private DataInputStream dis; //读入流
	private DataOutputStream dos; //读出流
	
	private ServerSocket server;// 服务器套接字
	private Socket socket;// 套接字
	private Test() {
	}// 缺省构造函数
	
	public static Test getTest() {
		return test == null ? new Test() :test;
	}

	public void startServer()// 启动服务器
	{
		try {
			server = new ServerSocket(1024);// 创建服务器套接字
			System.out.println("服务器套接字建立完毕");

				System.out.println("等待客户端GG");
				socket=server.accept(); //若客户端GG提出连接请求,与socket连接  
				System.out.println("完成与客户端的连接");
//				reader = new BufferedReader(new InputStreamReader(socket
//						.getInputStream(), "UTF-8"));
				// 获取socket输入流,“utf-8”
				// 这个编码设置是为了更好显示中文
				System.out.println("begin time getOutput is:" + System.currentTimeMillis());

				dos = new DataOutputStream(socket.getOutputStream());
				
				System.out.println("end time getOutput is:" + System.currentTimeMillis());

				getMessage();// 读取来自客户端的数据,并输出至画面上 

		} catch (Exception e) {
			System.out.println(e);
		} finally {
			try {
				if (server != null)
					server.close();// 关闭服务器套接字。
			} catch (IOException ie) {
			}
		}
	}

	public void getMessage()// 读取来自套接字的信息
	{

			try {
			while (true) {
				System.out.println("begin time is:" + System.currentTimeMillis());
				String s = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8")).readLine();
				System.out.println("来自客服端的消息:"+ s);
				System.out.println("end time is:" + System.currentTimeMillis());
				/*************--??--************/
//				dis = new DataInputStream(socket.getInputStream());
//				dos = new DataOutputStream(socket.getOutputStream());
				System.out.println("s is: " +s);
				String test;

				switch (ran.nextInt(3)) {
				case 1:
					test = "石头";
					break;
				case 2:
					test = "剪刀";
					break;
				default:
					test = "布袋";
					break;
				}
				
				if (s != null) {
					if (s.equals(test)) {
						dos.writeUTF("什么玩意儿啊 都是"+test+" 平了");
						dos.flush();
					}else if (s.equals("剪刀")) {
						if (test.equals("石头")) {
							dos.writeUTF("随便出石头也赢!");
							dos.flush();
						}else {
							dos.writeUTF(" 靠,我是布袋你是剪刀你赢了!!");
							dos.flush();
						}
					}else if (s.equals("布袋")) {
						if (test.equals("石头")) {
							dos.writeUTF("我石头你布袋你赢了!!");
							dos.flush();
						}else {
							dos.writeUTF("随便出剪刀也赢!");
							dos.flush();
						}
					}else if (s.equals("石头")) {
						if (test.equals("布袋")) {
							dos.writeUTF("随便出布袋也赢!");
							dos.flush();
						}else {
							dos.writeUTF(" 靠,我是剪刀你是石头你赢了!!");
							dos.flush();
						}
				   }else {
					   dos.writeUTF("出的什么东西不知道了"); 
					   dos.flush();
				   }
				}
			}	
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
	public static void main(String[] args) {
		Test test = Test.getTest();
		System.out.println("------------测试开始------------------");
		test.startServer();
		System.out.println("-------------测试结束------------------");
	}


一种现象当客服端关闭时:
服务器端一直输出 null的查究:
个人想法是:
  服务器端
a 开启socket连接 .
b 从socket上面取得数据
这两个操作其实都是一个等待监听的过程(说白了就是只有当客服端有连接 或者 socket输出流<该流针对客服端是输入流>上有数据时java代码才继续往下运行)~ 这也是 为什么要用while (true) 循环的原因

当客服端页面主动关闭时 输入流从客服端输入数据已经不可能,那么既然已经不存在输入了,那服务器端等待输出流里面有数据已经不存在等待了...拿拿到的数据自然是null...

我想程序设计者完全可以杜绝这种现象,但是如果杜绝又拿什么来判断客服端已经被关闭了呢
这也是为什么输出null的一个原因吧....


附件的说明:
可以自己往MyEclipse开发环境中导~ 前期已把flex开发环境置于MyEclipse中
本例中要用到的主要文件有:
Test.java sorcket.mxml 其它的可以说是多余
如可操作 访问??
  1:调用Test.java 中main函数
  2:访问sorcket.swf 文件 就OK了  记得不用开启tomcat~
 
分享到:
评论
1 楼 hhzy 2010-01-11  
支持下lz

相关推荐

Global site tag (gtag.js) - Google Analytics