`

Java与Flex通信

阅读更多

Flex连接Java Server

首先向Server发送了

 

final static String security_req = "<policy-file-request/>"; 

   

继而Server端返回

 

public final String flexString = "<cross-domain-policy>\n" + " <allow-access-from domain=\"*\" to-ports=\"*\" />\n" + "</cross-domain-policy>";

 

可以开始正常通信。Client端和Server端输出如下:

 

Client:9099

> <policy-file-request/>
...sending <policy-file-request/>...
<cross-domain-policy>
  <allow-access-from  domain="*"  to-ports="*"  />
</cross-domain-policy>
> 123
...sending 123...
alarm

'''
Created on 2009-3-18

@author: Administrator
'''

from twisted.internet import protocol, reactor
from time import ctime

HOST = '192.168.0.93'
PORT = 9099

class TSClntProtocol(protocol.Protocol):
    def sendData(self):
        data = raw_input('> ')
        if data:
            print '...sending %s...' % data
            self.transport.write(data)
        else:
            self.transport.loseConnection()
            
    def connectionMade(self):
        self.sendData() 
        
    def dataReceived(self, data):
        print data
        self.sendData()
        
class TSClntFactory(protocol.ClientFactory):
    protocol = TSClntProtocol
    clientConnectionLost = clientConnectionFailed = lambda self, connector, reason:reactor.stop()
    
reactor.connectTCP(HOST, PORT, TSClntFactory())
reactor.run()

 

 

 

Client:9090

telnet 至9090端口并输入即可。

 

Server

package server.tcp.receive;

// $Id: ServerImpCopy.java,v 1.3 2009/03/27 03:59:05 cvsjyy Exp $

import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import server.alarm.NBlockingServer;
import server.log.LoggerFactory;

public class ServerImpCopy implements IServer {
	// The port we will listen on
	private int port;

	// A pre-allocated buffer for encrypting data
	private ByteBuffer btBffr;

	//
	private ServerSocketChannel srvrScktChnnl;

	private ServerSocket srvrSckt;

	private InetSocketAddress isa;

	private Selector selector;

	/**
	 * */
	private Logger logger = LoggerFactory.initLogger();

	private Queue queue = null;

	// private boolean initialFlag = true;

	public ServerImpCopy(Queue queue) {
		this.queue = queue;
	}

	/**
	 * @param port
	 *            The port to set.
	 */
	public void setPort(int port) {
		this.port = port;
	}

	private void init() throws IOException {

		this.btBffr = ByteBuffer.allocate(2048);
		this.srvrScktChnnl = ServerSocketChannel.open();

		// Set it to non-blocking, so we can use select
		this.srvrScktChnnl.configureBlocking(false);

		// Get the Socket connected to this channel, and bind it
		// to the listening port
		this.srvrSckt = srvrScktChnnl.socket();
		this.isa = new InetSocketAddress(this.port);
		// ss.bind(isa);
		try {
			srvrSckt.bind(isa);
		} catch (BindException e) {
			logger.error("Unable to bind to port " + isa);

			System.exit(1);

		}

		// Create a new Selector for selecting
		selector = Selector.open();

		// Register the ServerSocketChannel, so we can
		// listen for incoming connections
		srvrScktChnnl.register(selector, SelectionKey.OP_ACCEPT,
				new ChannelBuffer());
	}

	public void run() throws IOException {
		init();
		while (true) {
			// See if we've had any activity -- either
			// an incoming connection, or incoming data on an
			// existing connection
			int num = selector.select();

			// If we don't have any activity, loop around and wait
			// again
			if (num == 0) {
				continue;
			}

			// Get the keys corresponding to the activity
			// that has been detected, and process them
			// one by one
			Set<?> keys = selector.selectedKeys();
			Iterator<?> it = keys.iterator();
			while (it.hasNext()) {
				// Get a key representing one of bits of I/O
				// activity
				SelectionKey slctonk = (SelectionKey) it.next();

				// What kind of activity is it?
				if ((slctonk.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
					logger.log(Level.INFO, "accept");
					// It's an incoming connection.
					// Register this socket with the Selector
					// so we can listen for input on it

					Socket socket = srvrSckt.accept();
					logger.log(Level.INFO, "Got connection from " + socket);

					// Make sure to make it non-blocking, so we can
					// use a selector on it.
					SocketChannel scktChnnl = socket.getChannel();
					scktChnnl.configureBlocking(false);

					// Register it with the selector, for reading
					scktChnnl.register(selector, SelectionKey.OP_READ,
							new ChannelBuffer());
				} else if ((slctonk.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

					SocketChannel scktChnnl = null;

					try {
						// It's incoming data on a connection, so
						// process it
						scktChnnl = (SocketChannel) slctonk.channel();
						ChannelBuffer channelBuffer = (ChannelBuffer) slctonk
								.attachment();
						byte[] result = processInput(scktChnnl, channelBuffer);

						// If the connection is dead, then remove it
						// from the selector and close it
						if (result.length == 0) {
							slctonk.attach(null);
							slctonk.cancel();
							logger.info("release the attachement 1.");
							Socket s = null;
							try {
								s = scktChnnl.socket();
								s.close();
							} catch (IOException ie) {
								logger.error("Error closing socket " + s + ": "
										+ ie);
							}
						}

						/*
						 * echo
						 */
						ByteBuffer buf = ByteBuffer.allocate(result.length);
						buf.put(result);
						buf.flip();
						int nbytes = scktChnnl.write(buf);
						logger.info("nbytes is: " + nbytes);
						/*
						 * broadcast
						 */
						Set<?> bKeys = this.selector.keys();
						int i = 0;

						Iterator<?> bIt = bKeys.iterator();
						while (bIt.hasNext()) {
							SelectionKey bKey = (SelectionKey) bIt.next();
							logger.info("flex connection:");
							logger.info(i);
							i++;
							if ((bKey.interestOps() & SelectionKey.OP_READ) != 0) {
								SelectableChannel channel = (SelectableChannel) bKey
										.channel();

								SocketChannel sChannel = (SocketChannel) channel;
								ByteBuffer bBuf = ByteBuffer
										.allocate(result.length);
								bBuf.put(result);
								bBuf.flip();
								int tmpnbytes = sChannel.write(bBuf);
								logger.info("tmpnbytes is: " + tmpnbytes);
								logger.info("ContentsAlarm send to Flex!");
								// writeToChannel((SocketChannel) channel,
								// "alarm to XZC");

							} else
								continue;
						}
						/* send to flex */
						NBlockingServer ns = NBlockingServer
								.getNBlockingServer();
						ns.reportAlarm("alarm");

					} catch (IOException ie) {

						// On exception, remove this channel from the
						// selector
						slctonk.attach(null);
						slctonk.cancel();
						logger.info("release the attachement 2.");
						try {
							scktChnnl.close();
						} catch (IOException ie2) {
							logger.error(ie2);
						}
						logger.error("Closed " + scktChnnl);
					}
				}
			}

			// We remove the selected keys, because we've dealt
			// with them.
			keys.clear();
		}

	} // Do some cheesy encryption on the incoming data,

	// and send it back out
	private byte[] processInput(SocketChannel sc, ChannelBuffer channelBuffer)
			throws IOException {
		logger.info("method of processInput start");

		byte[] result = new byte[0];

		btBffr.clear();
		sc.read(btBffr);
		btBffr.flip();

		// If no data, close the connection
		if (btBffr.limit() == 0) {
			return result;
		}

		/**/
		btBffr.position(0);

		/**/
		result = new byte[btBffr.limit()];

		btBffr.get(result);

		/**/
		logger.info("Processed " + btBffr.limit() + " from " + sc);

		/**/
		// channelBuffer.setBuffer(tmpBuffer);
		/**/
		logger.info("method of processInput end ");
		return result;
	}

	public static void main(String args[]) throws Exception {

		// ApplicationContext context = SpringContext.getContext();
		// IServer tcpServer = (IServer) context.getBean("tcpReceiver");
		// send alarm to flex
		Thread t1 = new Thread(NBlockingServer.getNBlockingServer());
		t1.start();
		//
		// // Consumer Thread
		// PckgHandler ph = new PckgHandler(Queue.getQueue());
		// Thread t2 = new Thread(ph);
		// t2.start();

		// main thread
		int port = 9090;
		// IServer tcpServer = (IServer) SpringContext.getBean("tcpReceiver");
		ServerImpCopy tcpServer = new ServerImpCopy(Queue.getQueue());
		tcpServer.setPort(port);
		tcpServer.run();

	}

}

 

 

 

Server执行其他逻辑,在得到某些信息后,取得Socket的句柄,向Flex发送信息。另外,回想我们以前写过的NIO的客户端回显及广播的程序。我们尝试将在9090端口得到的数据除了在发送端回显,并向9090的所有Client广播,此外我们将通知Flex,也就是9099Client一个alarm

分享到:
评论

相关推荐

    java与flex通信

    Java与Flex通信主要依赖于Adobe的BlazeDS技术,它提供了一个基于HTTP的实时双向通信框架,使得ActionScript(Flex的编程语言)可以与后端的Java服务进行数据交互。以下将详细介绍如何实现这一通信过程。 1. **...

    最简单的java与flex通信实例与完全步骤总结

    本篇文章将详细介绍一个最简单的Java与Flex通信的实例,并提供完整的实现步骤。 1. **Flex简介**: Flex是Adobe公司推出的一种基于ActionScript的开源框架,用于创建富互联网应用程序(RIA)。它使用MXML和...

    Java与Flex通信的Java端代码

    在“JavaFlex项目”这个压缩包中,很可能包含了使用Java和Flex进行通信的示例代码,包括Java端的服务实现、BlazeDS配置以及Flex端的HTTPService或WebService调用。通过分析和学习这些代码,你可以更好地理解和掌握...

    使用BlazeDS实现Java和Flex通信

    ### 使用BlazeDS实现Java和Flex通信:详细指南与步骤 BlazeDS是Adobe公司推出的一款开源工具,它充当了一座桥梁,使后端的Java应用程序能够与前端的Adobe Flex应用程序进行实时通信。通过BlazeDS,开发者可以构建出...

    用BlazeDS实现Java和Flex通信

    ### 使用BlazeDS实现Java与Flex通信的关键知识点 #### 一、引言 随着Web技术的发展,前后端的通信方式也变得越来越多样化。其中,Flex作为一种流行的应用开发框架,经常被用于构建丰富的互联网应用程序(RIA)。...

    java+flex通信源码

    这个"java+flex通信源码"项目提供了一个实际的、完整的示例,演示了如何利用BlazeDS技术实现Java后端与Flex前端的无缝交互。下面我们将深入探讨相关的知识点。 首先,Flex是一种基于ActionScript的开放源代码框架,...

    通过MyEclpise整合JAVA与FLEX进行通讯(通过将Flex工程加到Java web工程中)

    此外,理解MXML和ActionScript的数据绑定机制,以及Java中的序列化和反序列化过程,对于实现高效的JAVA与FLEX通信至关重要。 总之,通过MyEclipse整合JAVA与FLEX,可以构建出功能强大的、用户体验丰富的Web应用。这...

    flex与java通信

    Flex和Java之间的通信是Web应用程序开发中的一个重要环节,它允许前端用户界面(UI)与后端服务器进行数据交互。Flex是一种基于Adobe Flash Player或Adobe AIR运行时的富互联网应用程序(RIA)开发框架,而Java则是...

    Flex与Java实现通信

    ### Flex与Java实现通信——使用BlazeDS技术详解 #### 一、引言 随着互联网技术的不断发展,前端与后端之间的数据交换变得越来越频繁。Adobe Flex作为一种强大的RIA(Rich Internet Applications)技术,广泛应用...

    通过SmartInvoke运用java与flex轻松构建cs程序.doc

    #### Java与Flex通信 - **创建服务类型(Service Class Type)** 实现Flex直接调用Java的方法需要创建实现了`cn.smartinvoke.IServerObject`接口的服务类。 - 使用`Eclipse`工具栏中的相应图标创建服务类型。 - ...

    Java_Flex,Java_Flex,Java_Flex

    1. BlazeDS:BlazeDS是Adobe官方提供的一个免费的中间件,它允许Java服务器与Flex客户端之间进行实时双向通信。BlazeDS支持AMF(Action Message Format)协议,这是一种高效的二进制数据格式,能大幅减少网络传输...

    Java与Flex开发入门

    通过使用AMF(Action Message Format)或其他数据交换格式,如JSON或XML,Java服务器可以与Flex客户端进行高效的数据通信。这种方式允许Flex应用程序充分利用Java的强大计算能力和企业级服务,同时保持富媒体和交互...

    java与flex的通信

    1. **Java环境配置**:首先,你需要在Java环境中安装 BlazeDS 或 LCDS(LiveCycle Data Services),这两个是Adobe提供的服务器组件,它们提供了与Flex通信的AMF通道。BlazeDS是开源的,而LCDS是商业版本,具有更多...

    使用BlazeDS实现Java和Flex通信之hello world

    这个“使用BlazeDS实现Java和Flex通信之hello world”示例旨在介绍如何通过BlazeDS来实现简单但关键的客户端-服务器交互。下面我们将详细探讨BlazeDS、Flex以及它们之间的通信机制,并通过“hello world”实例来具体...

    Flex_Java.rar

    描述中的"java与flex通信"进一步强调了这个主题,意味着压缩包的内容将专注于讲解Flex客户端如何与Java服务器进行数据交换。这种通信通常涉及到HTTP服务、AMF(Action Message Format)或者WebSocket等技术。 在...

    java+flex原码

    通过使用RESTful API或者SOAP Web服务,Java可以与Flex前端进行通信,传递数据和指令。 Flex作为前端,主要利用Adobe Flash Player或Adobe AIR运行,为用户提供动态、响应式的UI体验。它使用MXML和ActionScript语言...

Global site tag (gtag.js) - Google Analytics