Android app之间通过socket通信

一台手机作为server,另一台作为client,使用了Mina框架。

一. Server端代码如下:

 NioSocketAcceptor localNioSocketAcceptor = new NioSocketAcceptor();
        TextLineCodecFactory localTextLineCodecFactory = new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), "/r/n");
        localTextLineCodecFactory.setDecoderMaxLineLength(10240);
        localTextLineCodecFactory.setEncoderMaxLineLength(10240);
        localNioSocketAcceptor.getFilterChain().addLast("textProtocol", new ProtocolCodecFilter(localTextLineCodecFactory));
        localNioSocketAcceptor.getSessionConfig().setReadBufferSize(2048);
        localNioSocketAcceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        ((NioSocketAcceptor)localNioSocketAcceptor).setReuseAddress(true);
        localNioSocketAcceptor.setHandler(new ServerHandler(this.context));
        try
        {
            localNioSocketAcceptor.bind(new InetSocketAddress(8801));
            Toast.makeText(this.context, "服务器启动成功,端口号:" + 8801, Toast.LENGTH_SHORT).show();
            return;
        }
        catch (IOException localIOException)
        {
            localIOException.printStackTrace();
        }

监听Handler类:

public class ServerHandler extends IoHandlerAdapter {

    private Context context;

    public ServerHandler(Context paramContext) {
        this.context = paramContext;
    }

    public void exceptionCaught(IoSession paramIoSession, Throwable paramThrowable)
            throws Exception {
    }

    public void messageReceived(IoSession paramIoSession, Object paramObject)
            throws Exception {
        final String str = paramObject.toString();
        ((Activity) this.context).runOnUiThread(new Runnable() {
            public void run() {
                if (str != null) ;
                try {
                    KeyWord localKeyWord = GsonUtils.jsonToBean(str,KeyWord.class);
                    EventBus.getDefault().post(localKeyWord);
                    return;
                } catch (Exception localException) {
                }
            }
        });
    }

    public void messageSent(IoSession paramIoSession, Object paramObject)
            throws Exception {
        Toast.makeText(this.context, "messageSent:" + paramObject, Toast.LENGTH_SHORT).show();
    }

    public void sessionClosed(IoSession paramIoSession)
            throws Exception {
    }

    public void sessionCreated(IoSession paramIoSession)
            throws Exception {
    }

    public void sessionIdle(IoSession paramIoSession, IdleStatus paramIdleStatus)
            throws Exception {
    }

    public void sessionOpened(IoSession paramIoSession)
            throws Exception {
    }

}

二. client端代码:

 

  private void sendWordSocket(String paramString) {
        initSocket();
        KeyWord localKeyWord = null;
        if ((paramString != null) && (paramString.length() > 0) && (this.session != null) && (this.session.isConnected()))
            localKeyWord = new KeyWord(paramString);
        try {
            if (localKeyWord == null) return;
            this.session.write(new String((GsonUtils.beanToJson(localKeyWord) + "/r/n").getBytes(), "utf-8"));
            return;
        } catch (UnsupportedEncodingException localUnsupportedEncodingException) {
            localUnsupportedEncodingException.printStackTrace();
        }
    }


    private void initSocket() {
        try {
            String ip = PreferenceUtil.getInstance(this).getString("speech_socket_url", "");
            if ((ip == null) || (ip.length() == 0)) {
                Toast.makeText(this, "须配置socket地址", Toast.LENGTH_SHORT).show();
                return;
            }

            if ((this.session == null) || (!this.session.isConnected())) {
                NioSocketConnector localNioSocketConnector = new NioSocketConnector();
                MinaClientHanlder localMinaClientHanlder = new MinaClientHanlder();
                TextLineCodecFactory localTextLineCodecFactory = new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), "/r/n");
                localTextLineCodecFactory.setDecoderMaxLineLength(10240);
                localTextLineCodecFactory.setEncoderMaxLineLength(10240);
                localNioSocketConnector.getFilterChain().addLast("textProtocol", new ProtocolCodecFilter(localTextLineCodecFactory));
                localNioSocketConnector.getSessionConfig().setReadBufferSize(1048576);
                InetSocketAddress localInetSocketAddress = new InetSocketAddress(ip, 8801);
                localNioSocketConnector.setConnectTimeoutMillis(60000L);
                localNioSocketConnector.setHandler(localMinaClientHanlder);
                ConnectFuture localConnectFuture = localNioSocketConnector.connect(localInetSocketAddress);
                localConnectFuture.awaitUninterruptibly();
                this.session = localConnectFuture.getSession();
                return;
            }
        } catch (final Exception localException) {
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),localException.toString(),Toast.LENGTH_LONG).show();
                }
            });
        }
    }


    public class MinaClientHanlder extends IoHandlerAdapter {
        public MinaClientHanlder() {
        }

        public void messageReceived(IoSession paramIoSession, Object paramObject)
                throws Exception {
            System.out.println("客户端接受到了消息" + paramObject);
        }

        public void sessionClosed(IoSession paramIoSession) {
            System.out.println("client close");
        }

        public void sessionOpened(IoSession paramIoSession)
                throws Exception {
            System.out.println("客户端登陆");
            Toast.makeText(MainActivity.this, "客户端登陆", Toast.LENGTH_SHORT).show();
        }
    }


顺序:server通过localNioSocketAcceptor.bind(new InetSocketAddress(8801));绑定监听8801端口,设置handler回调消息,

    client端连接到server端,并通过this.session.write(new String((GsonUtils.beanToJson(localKeyWord) + "/r/n").getBytes(), "utf-8"));与server端通信。其中client中的ip必须为server的ip,且端口要统一。



  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值