wxg630
wxg3715
2017-11-19 13:05

mina udp 客户端收不到服务端消息

15
  • mina udp 客户端

已经关闭防火墙,抓包工具可以监听到服务端已经发送了消息
客户端代码 package cn.encdata.service.signal.realtime.client;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
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.NioDatagramConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.encdata.service.Config;

//通信客户端
public class SocketClient
{
private ConnectFuture future = null;//连接对象
private boolean exit = false;
private static Charset CS = Charset.forName("GBK");
private IoSession session = null;//会话
private static Logger log = LoggerFactory.getLogger(SocketClient.class);
private static SocketClient client= null;

private SocketClient()
{

}

public static SocketClient instance()
{
    if(client == null)
    {
        client = new SocketClient();
    }
    return client;
}

public synchronized void start()
{
    new Thread(new Runnable(){
        public void run(){connect();}
    }).start();
}


public synchronized void stop()
{
    if(future!=null && future.isConnected())
    {
        future.getSession().close(true);
        future = null;
        exit = true;
    }
}

public synchronized void send(IoBuffer buffer)
{
    if(buffer == null) return;
    if(session == null || !session.isConnected())
    {
        log.info("通讯链路尚未创建,无法发送数据.");
        return;
    }
    if(session.getAttribute("login") == null)
    {
        log.info("通讯链路尚未通过验证,无法发送数据.");
        return;
    }
    session.write(buffer);
    buffer.free();
}

private void connect()
{
    while(!exit)
    {
        if(future == null || !future.isConnected())
        {
            IoConnector connector = null;
            try 
            {

                connector = new NioDatagramConnector();
                connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));
                //connector.setConnectTimeoutMillis(Config.Server.ConnectTimeout);
                connector.setHandler(new SocketDataHandler());
                future = connector.connect(new InetSocketAddress("172.16.13.99",5555),new InetSocketAddress("172.163.133.200",8341));
                future.awaitUninterruptibly();
                if (!future.isConnected())
                {
                    log.info(" 断线连接中{}:{}",Config.Server.IP,Config.Server.Port);
                    Thread.sleep(Config.Server.ReconnectInterval);
                    continue;
                }
                session = future.getSession();
                future.getSession().getCloseFuture().awaitUninterruptibly();
                future = null;
            }
            catch (Exception e)
            {
                log.error("创建通讯连接异常",e);
                break;
            }
            finally
            {
                if(connector != null)
                {
                    connector.dispose();
                }
            }
        }
        try 
        {
            Thread.sleep(Config.Server.ReconnectInterval);
        } 
        catch (InterruptedException e) 
        {
            e.printStackTrace();
        }
    }
}

}

handler类代码为:
package cn.encdata.service.signal.realtime.client;

import java.nio.ByteOrder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.encdata.service.Config;
import cn.encdata.service.signal.realtime.receive.handler.FaceHandler;

public class SocketDataHandler extends IoHandlerAdapter
{
private final Logger log = LoggerFactory.getLogger(SocketDataHandler.class);

@Override
public void sessionOpened(IoSession session)
{
    log.info("与服务器连接成功:"+session.getRemoteAddress());
   log.info("发送登录消息");
   //退出登录
   //session.write("退出登录\rsuper\r");
   session.write("登录系统\rsuper\r111\r");
}
@Override
public void sessionClosed(IoSession session) throws Exception 
{
    log.info("{}与服务器断线",session.getRemoteAddress());

}

@Override
public void messageReceived(IoSession session, Object message) 
{  


     System.out.println("客户端传来消息:"+message.toString());  




}

@Override
public  void sessionIdle(IoSession session, IdleStatus status) 
{
    if (status == IdleStatus.BOTH_IDLE)  
    {
        //发送心跳包
        IoBuffer heartbeat = IoBuffer.allocate(2+1);
        heartbeat.order(ByteOrder.BIG_ENDIAN);
        //heartbeat.putUnsignedShort(1);
        //heartbeat.putUnsigned(0);
        //heartbeat.flip();
        log.info("发送心跳消息");
        session.write("客户端正常\rsuper\r");
    }
}

@Override  
public void sessionCreated(IoSession session) throws Exception {  //当创建一个新的连接时被触发,即开始一个新的session是被触发
    log.info("sessionCreated");
    session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 20);  
}

@Override
public void messageSent(IoSession session, Object message) 
{

}

@Override
public void exceptionCaught(IoSession session, Throwable cause)
{
    log.error(cause.getMessage(),cause);
}

}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换