---
title: "flex与java的socket通信"
author: "east_java"
date: "2009-03-25T15:16:07Z"
tags: []
slug: "flex-java-socket"
draft: false
lastmod: "2009-03-25T15:16:07Z"
id: 354841
url: "https://japi.iteye.com/blog/354841"
---

网上的示例很多

比如<http://www.java1995.cn/article/688.html>

记下注意点：

flex接受数据


前台代码：

```java

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Style>
	Button{
		border-style:solid;
		border-color:red;
		background-color:green;
		backgroundColor:green;
	}
</mx:Style>

<mx:Script>
	<![cdata[
		import com.sunshine.core.socket.socketmanager;
		var socket:socket = new Socket();
		public function init():void{
			socket.connect("127.0.01.1",8888);
			socket.addEventListener(Event.CONNECT,funConnect);
			socket.addEventListener(ProgressEvent.SOCKET_DATA,funSocket);
			var b:ByteArray = new ByteArray();
			b.writeUTF("code");
			socket.writeBytes(b);
		}
		public function funConnect(event:Event){
			conB.label="connection success";
		}
		var bytes:ByteArray =new ByteArray();
		public function funSocket(event:Event){
			var bb:ByteArray = new ByteArray();
			trace("--write------");
			//if (c.bytesAvailable>0){
				trace("can read");
			var image:String 
			rece();
		}
		public function connection():void{
			rece();
		}
		
		public function rece():void{
			while (socket.bytesAvailable) {
 				trace("available");
 				 socket.readBytes(bytes,0,socket.bytesAvailable);
 				 conB.label=bytes.readUTF();			 
			}
		}
	]]>
</mx:Script>
	<mx:Button id="conB" x="125" y="167" width="207" height="61" click="connection()">
	</mx:Button>
</mx:Application>

```



注意
接受数据必须加上接受事件：
```java
socket.addEventListener(ProgressEvent.SOCKET_DATA,funSocket);
```


<span style="color:red">不能只写在一个组件的触发事件里面，否则接受不到数据。</span>