mina 简单实例(传送文本的)

原创 2007年10月08日 11:05:00

SeverTest.java

/**
 * Copyright TopScientific Systems Ltd. 2005-2007
 * All right reserved.
 */
package org.apache.mina.mytest;


import java.net.InetSocketAddress;

import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.IoAcceptorConfig;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

/**
 * @author zkchen
 *
 */
public class SeverTest {

 private static final int PORT = 1234;
 public static void main(String[] args) throws Exception {

  IoAcceptor acceptor = new SocketAcceptor();
  IoAcceptorConfig config = new SocketAcceptorConfig();
  DefaultIoFilterChainBuilder chain = config.getFilterChain();

  // Add SSL filter if SSL is enabled.

  chain.addLast("codec", new ProtocolCodecFilter(
    new TextLineCodecFactory()));

  addLogger(chain);

  // Bind
  acceptor.bind(new InetSocketAddress(PORT), new EchoProtocolHandler(
    ), config);

  System.out.println("Listening on port " + PORT);

 }

 private static void addLogger(DefaultIoFilterChainBuilder chain)
   throws Exception {
  chain.addLast("logger", new LoggingFilter());
  System.out.println("Logging ON");
 }
}

EchoProtocolHandler.java

 

package org.apache.mina.mytest;

import java.util.Hashtable;

import java.util.Iterator;

import java.util.Random;

import org.apache.mina.common.ByteBuffer;

import org.apache.mina.common.IdleStatus;

import org.apache.mina.common.IoHandler;

import org.apache.mina.common.IoHandlerAdapter;

import org.apache.mina.common.IoSession;

import org.apache.mina.common.TransportType;

import org.apache.mina.filter.SSLFilter;

import org.apache.mina.transport.socket.nio.SocketSessionConfig;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

public class EchoProtocolHandler extends IoHandlerAdapter {

 private static final Logger log = LoggerFactory

   .getLogger(EchoProtocolHandler.class);

 private Hashtable<IoSession, String> clients = new Hashtable<IoSession, String>();

 private Random random = new Random();;

 private static int user = 0;

 public EchoProtocolHandler() {

  super();

 }

 public void sessionCreated(IoSession session) {

  if (session.getTransportType() == TransportType.SOCKET) {

   ((SocketSessionConfig) session.getConfig())

     .setReceiveBufferSize(2048);

  }

  session.setIdleTime(IdleStatus.BOTH_IDLE, 10);

  // We're going to use SSL negotiation notification.

  session.setAttribute(SSLFilter.USE_NOTIFICATION);

  // session.write("create a session");

 }

 public void sessionOpened(IoSession session) {

  // UserInfo userInfo = new UserInfo();

  // userInfo.isValid = false;

  // session.setAttachment(userInfo);

  String userName = "client" + (++user);

  session.write("session open");

  clients.put(session, userName);

  session.write("LOGIN OK");

  broadcast("The user " + user + " has joined the chat session. "

    + this.getNumberOfUsers());

  log.info("a new client connected,but didn't join yet!"); // 通话session

  // 打开以后促发的事件处理

  this.sendMessage(session);

 }

 public void sessionClosed(IoSession session) {

  log.info("a client closed,and now count is : "

    + this.getNumberOfUsers()); // 通话session

  String user = clients.get(session);

  clients.remove(session);

  broadcast("The user " + user + " has left the chat session.");

  // 关闭以后促发的事件处理

 }

 public void sessionIdle(IoSession session, IdleStatus status) {

  log.info("*** IDLE #" + session.getIdleCount(IdleStatus.BOTH_IDLE)

    + " ***");

  // session.write("sessionidle");

 }

 public void exceptionCaught(IoSession session, Throwable cause) {

  cause.printStackTrace();

  session.close();

 }

 public void messageReceived(IoSession session, Object message)

   throws Exception {

  if (!(message instanceof ByteBuffer)) {

   return;

  }

  ByteBuffer rb = (ByteBuffer) message;

  // Write the received data back to remote peer

  ByteBuffer wb = ByteBuffer.allocate(rb.remaining());

  wb.put(rb);

  wb.flip();

 }

 public void messageSent(IoSession session, Object message) {

  log.info(">>>>>this is server ,sent the message to client: ");

  log.info("messageSent succful");

  // 发送成功以后会调用这里的函数

  // message 为messageReceived 函数中 write 发送的消息

  // 绝对不要在这里用write 不然要死循环的

 }

 public void sendMessage(IoSession session) {

  int num;

  while(true) {

   try {

    Thread.sleep(1000);

   } catch (InterruptedException e) {

    e.printStackTrace();

   }

   num = random.nextInt();

   Iterator iter = clients.keySet().iterator();

   while (iter.hasNext()) {

    IoSession s = (IoSession) iter.next();

    if (s.isConnected()) {

     s.write("BROADCAST OK " + num);

    }

   }

  }

 }

 public void broadcast(String message) {

//

//  Iterator it=

//  while(it.hasNext())

//  {   System.out.println(clients.get(it.next()));}

  Iterator iter = clients.keySet().iterator();

  while (iter.hasNext()) {

   IoSession s = (IoSession) iter.next();

   if (s.isConnected()) {

    s.write("BROADCAST OK " + message);

   }

  }

  

 

 }

 public int getNumberOfUsers() {

  return clients.size();

 }

}

 

 

ClientTest.java

 

/**
 * Copyright TopScientific Systems Ltd. 2005-2007
 * All right reserved.
 */
package org.apache.mina.mytest;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoConnector;
import org.apache.mina.transport.socket.nio.SocketConnector;
import org.apache.mina.transport.socket.nio.SocketConnectorConfig;

 


/**
 * @author zkchen
 *
 */
public class ClientTest {
 //private  IoSession session;
    public ClientTest() {
   
      IoConnector  ioConnector = new SocketConnector();
      SocketAddress address = new InetSocketAddress("localhost",1234);
         ConnectFuture future1 = ioConnector.connect(address ,new ClientHandler() , new SocketConnectorConfig());
         if( ! future1.isConnected() )
            {
                System.out.println("full is connected");
            }
        future1.join();
              if( ! future1.isConnected() )
              {
                 System.out.println("hsa connected");
              }
              System.out.println(future1);
              System.out.println(future1.getSession());
  
 }
 
 public static void main(String [] args){
  new ClientTest();
 }
 }
 

ClientHandler.java

 

package org.apache.mina.mytest;

import org.apache.mina.common.ByteBuffer;

import org.apache.mina.common.IoFilter;

import org.apache.mina.common.IoHandler;

import org.apache.mina.common.IoHandlerAdapter;

import org.apache.mina.common.IoSession;

import org.apache.mina.filter.LoggingFilter;

import org.apache.mina.filter.codec.ProtocolCodecFilter;

import org.apache.mina.filter.codec.textline.TextLineCodecFactory;

 

/* *

 * @author The Apache Directory Project (mina-dev@directory.apache.org)

 * @version $Rev$, $Date$

 */

public class ClientHandler extends IoHandlerAdapter {

 private static IoFilter LOGGING_FILTER = new LoggingFilter();

 private static IoFilter CODEC_FILTER = new ProtocolCodecFilter(

   new TextLineCodecFactory());

 public void sessionCreated(IoSession session) throws Exception {

  session.getFilterChain().addLast("codec", CODEC_FILTER);

  session.getFilterChain().addLast("logger", LOGGING_FILTER);

 }

 public void sessionOpened(IoSession session) throws Exception {

  session.write("client open");

 }

 public void messageReceived(IoSession session, Object message)

   throws Exception {

  if (!(message instanceof ByteBuffer)) {

   return;

  }

  ByteBuffer rb = (ByteBuffer) message;

  // Write the received data back to remote peer

  ByteBuffer wb = ByteBuffer.allocate(rb.remaining());

  wb.put(rb);

  System.out.println(wb.toString());

  wb.flip();

  

 }

 public void messageSent(IoSession session, Object message) {

//  session.write("hello");

  // 发送成功以后会调用这里的函数

  // message 为messageReceived 函数中 write 发送的消息

  // 绝对不要在这里用write 不然要死循环的

 }

 public void sessionClosed(IoSession session) throws Exception {

 }

}

 

mina 传输图片

package mina.example3; import java.net.InetSocketAddress; import org.apache.mina.filter.codec.Prot...
  • chengxu2011
  • chengxu2011
  • 2014-11-24 17:26:12
  • 3646

mina传递图片实例

  • 2013年08月15日 10:15
  • 1.7MB
  • 下载

使用MINA进行UDP通信实现数据导入

  • 2010年03月10日 10:26
  • 7.41MB
  • 下载

mina的高级使用,mina文件图片传送,mina发送文件,mina报文处理,mina发送xml和json

  • 2014年06月19日 15:40
  • 1.7MB
  • 下载

java apache mina 2.0 发送和接收 字节数组 byte[]

java apache mina 2.0 发送和接收 字节数组 byte[] 2011-06-22 11:22 客户端: public class ByteClient ...
  • liuzheng2684
  • liuzheng2684
  • 2011-10-31 11:37:12
  • 9533

Informix SQL语句查询器(v1.0)

  • 2003年03月30日 00:00
  • 8B
  • 下载

mina服务器--实现纯文本和非纯文本的加密通讯

  • 2015年04月21日 12:15
  • 4.45MB
  • 下载

Mina自定义文本编解码

前言:正如我们想的那样,文本的内容一次解析不完该怎么办呢?答案是用一个对象将这些未解析的对象存起来,等待解析。这个对象一般保存在session中。 1、文本编码器 package com.bo...
  • boonya
  • boonya
  • 2013-05-02 21:42:10
  • 1280

mina传输文件

mina传输对象已经不是什么难事,一般啃半天代码就能搞定,但是传输文件似乎不是很容易,之前在论坛上求助过但是没有解决,还是靠自己啃代码解决了文件的上传和下载,以下只是随便测试写的代码供学习用(只是有很...
  • viproc
  • viproc
  • 2012-08-07 15:09:16
  • 3113

Android 简单使用mina传递byte数组

具体使用的包可以参考http://www.2cto.com/kf/201606/515499.html,感谢作者的帮助 如果是在eclipse上,直接导入log4j-1.2.17.j...
  • HYL0406445
  • HYL0406445
  • 2016-11-18 11:27:00
  • 1905
收藏助手
不良信息举报
您举报文章:mina 简单实例(传送文本的)
举报原因:
原因补充:

(最多只允许输入30个字)