IM聊天进阶(三)IM>openfire>mina>mina搭建服务端和客户端 实现简单点对点聊天

mina果然方便!

先看效果

服务端:




2 客户端  1 孙俪



客户端2  朱茵



客户端3 男主角




材料:  mina209  slf4j-api  slf4j-log4j  log4j

 package mina1.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.HashMap;

import org.apache.log4j.PropertyConfigurator;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class MinaServer {
    private  static final int PORT=1113;
    private final static Logger LOGGER = LoggerFactory.getLogger(MinaServer.class);
   
 public static void main(String[] args) {
   PropertyConfigurator.configure ("log4j.properties");
   Commond.usersMap=new HashMap<String, IoSession>();
   
   
 try {
  IoAcceptor serverAcceptor=new NioSocketAcceptor();
   serverAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
   serverAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("utf-8"))));
  serverAcceptor.setHandler(new MyHandler());
  serverAcceptor.getSessionConfig().setReadBufferSize(2048);
  serverAcceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
  
  serverAcceptor.bind(new InetSocketAddress(PORT));
  
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
  

 }

}



Iohandler


package mina1.server;
 

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class MyHandler extends IoHandlerAdapter
{
  public String receivemsg="";
 
    @Override
 public void sessionCreated(IoSession session) throws Exception {
  
    // System.out.println("sessioncreaed:"+session.getId());
     
 }
 @Override
 public void sessionOpened(IoSession session) throws Exception {
  // TODO Auto-generated method stub
 //  System.out.println("sessionOpened:"+session.getId());
 }
 @Override
 public void inputClosed(IoSession session) throws Exception {
  System.out.println("inputClosed:"+session.getId());
 }
 @Override
 public void sessionClosed(IoSession session) throws Exception {
  System.out.println("有会话关闭sessionClosed:"+session.getId());
  super.sessionClosed(session);
 }
 @Override
    public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
    {
        cause.printStackTrace();
        System.out.println("服务器 exceptionCaught");
         session.close(true);
         //super.sessionClosed(session);
    }
    @Override
    public void messageReceived( IoSession session, Object message ) throws Exception
    {
        String str = message.toString();
        if( str.trim().equalsIgnoreCase("quit") ) {
            session.close(true);
            return;
        }
       // System.out.println("服务器收到的消息"+str);
        try {
         String[] msg=str.split(",");
          if (msg[0]!=null & msg[1]!=null)
          {
                 //是注册的
          if (msg[0].equals("reg"))
          {
            Commond.usersMap.put(msg[1], session);
            session.write(msg[1]+"欢迎您上线");
            System.out.println(msg[1]+"欢迎您上线");
           
          }
           //聊天信息 格式 //输入格式    msg,接收人,发送人,内容
          else if (msg[0].equals("msg")){
           IoSession sessionTarget=Commond.usersMap.get(msg[1]);
              sessionTarget.write(msg[2]+"说: "+msg[3]);
              System.out.println(msg[2]+"对"+msg[1]+"说:  "+msg[3]);
          }
       
          
          }
          else
          {
           session.write("消息不合规范");
          }
   
  } catch (Exception e) {
      session.write("拆分消息异常");
   
  }
      
    }
    @Override
 public void messageSent(IoSession session, Object message) throws Exception {
  
        //System.out.println("服务器转发消息:"+receivemsg+"--- mssage:"+message);
        
 }
 @Override
    public void sessionIdle( IoSession session, IdleStatus status ) throws Exception
    {
       // System.out.println( "服务器空闲 " + session.getIdleCount( status ));
    }
}



客户端

package mina1.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import mina1.server.MinaServer;

import org.apache.log4j.PropertyConfigurator;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MinaClient {

 private   final String HOSTNAME = "127.0.0.1";
 private   final int PORT = 1113;
 private   final long CONNECT_TIMEOUT = 3 * 1000L; // 30 seconds
 private     Logger LOGGER = LoggerFactory.getLogger(MinaServer.class);
    private NioSocketConnector clientConnector=null;
    private static  IoSession session=null;

 public static void main(String[] args) throws Throwable {
  
  PropertyConfigurator.configure("log4j.properties");
    MinaClient minaClient=new MinaClient();
    session=minaClient.regeditUser("张木生");
    if (session!=null)
    {
     minaClient.beginWork(session);
    }
    else {
   System.out.println("连接失败");
  }
 }
 
 public void beginWork(IoSession session)
 {
  // 聊天
  String inputstring;
  try {
   BufferedReader readin=new BufferedReader(new InputStreamReader(System.in));
   inputstring = readin.readLine();
   while (!inputstring.equals("bye")) {
               //输入格式    msg,接收人,发送人,内容
    session.write(inputstring);
    inputstring = readin.readLine();
   }
  } catch (IOException e) {
    System.out.println("BeginWOrk-->"+e.getMessage());
   
  }
  session.getCloseFuture().awaitUninterruptibly();
  clientConnector.dispose();
  
 }

 public IoSession regeditUser(String username)
 {
  IoSession session=null;
  
  NioSocketConnector clientConnector = new NioSocketConnector();
  clientConnector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
  // clientConnector.getFilterChain().addLast("logger", new
  // LoggingFilter());
  clientConnector.getFilterChain().addLast(
    "codec",
    new ProtocolCodecFilter(new TextLineCodecFactory(Charset
      .forName("utf-8"))));
  clientConnector.setHandler(new AppHandler());
  ConnectFuture future = clientConnector.connect(new InetSocketAddress(
    HOSTNAME, PORT));
  future.awaitUninterruptibly();
    session = future.getSession();
    session.write("reg"+","+username);
  return session;
  
  
  
  
 }
 
 
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值