简体   繁体   English

如何连接Apache Mina服务器使用Node.js?

[英]How to connect apache mina server use nodejs?

package com.buscontrol.site.message;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
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.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class Client extends IoHandlerAdapter {
    public static final int CONNECT_TIMEOUT = 30000;
    private String host;
    private int port;
    private SocketConnector connector;
    private IoSession session;
    public Object responsecontent = null;
    boolean retuanflag;

    public Object getResponsecontent() {
        return this.responsecontent;
    }

    public void setResponsecontent(Object responsecontent) {
        this.responsecontent = responsecontent;
    }

    public boolean isRetuanflag() {
        return this.retuanflag;
    }

    public void setRetuanflag(boolean retuanflag) {
        this.retuanflag = retuanflag;
    }

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
        this.connector = new NioSocketConnector();
        TextLineCodecFactory lineCodec = new TextLineCodecFactory(Charset.forName("UTF-8"));
        lineCodec.setDecoderMaxLineLength(1048576);
        lineCodec.setEncoderMaxLineLength(1048576);
        this.connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(lineCodec));
        this.connector.setHandler(this);
    }

    public boolean isConnected() {
        return this.session != null && this.session.isConnected();
    }

    public void connect() throws Exception {
        ConnectFuture connectFuture = this.connector.connect(new InetSocketAddress(this.host, this.port));
        connectFuture.awaitUninterruptibly(30000L);

        try {
            this.session = connectFuture.getSession();
            if(this.session == null) {
                throw new Exception("连接服务器失败");
            }
        } catch (RuntimeIoException var3) {
            this.connector.dispose();
            throw new Exception(var3.getMessage());
        }
    }

    public void disconnect() {
        if(this.session != null) {
            this.session.close(true).awaitUninterruptibly(30000L);
            this.session = null;
            this.connector.dispose();
        }

    }

    public void sessionOpened(IoSession session) throws Exception {
    }

    public void sessionClosed(IoSession session) throws Exception {
    }

    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        session.close(true);
    }

    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
        SocketSessionConfig cfg = (SocketSessionConfig)session.getConfig();
        cfg.setReceiveBufferSize(2097152);
        cfg.setReadBufferSize(2097152);
        cfg.setKeepAlive(true);
        cfg.setSoLinger(0);
    }

    public void sendRequest(String request) throws Exception {
        if(this.session == null) {
            throw new Exception("没有连接,请重新登录连接服务器");
        } else {
            this.session.write(request);
        }
    }

    public void messageReceived(IoSession session, Object message) throws Exception {
        String response = (String)message;
        JSONObject ja = null;

        try {
            ja = (JSONObject)JSONSerializer.toJSON(message);
            this.responsecontent = ja;
        } catch (Exception var6) {
            this.responsecontent = null;
        }

        this.retuanflag = true;
    }

    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        session.close(true);
        System.out.println(cause.getMessage());
    }

    public static void main(String[] args) throws Exception {
        Client c = new Client("localhost", 8698);
        c.connect();
        c.sendRequest("连接测试1");

        try {
            Thread.sleep(2000L);
        } catch (InterruptedException var3) {
            var3.printStackTrace();
        }

    }

    private Object getResponseObject(JSONObject ja) throws Exception {
        Object response = null;

        try {
            if(ja != null) {
                response = ja.get("result");
                if(response == null) {
                    throw new Exception();
                } else {
                    return response;
                }
            } else {
                throw new Exception();
            }
        } catch (Exception var4) {
            throw new Exception("请求消息格式不正确,缺少请求参数");
        }
    }
}

The code above used to connect mina server: 上面的代码用于连接Mina服务器:

Now, I want do it with nodejs. 现在,我想用nodejs来做。 I only find this on internet. 我只能在互联网上找到它。

Sending message to MINA socket server from Node JS Socket client 从Node JS Socket客户端向MINA套接字服务器发送消息

I tried frame-streamnet.Socket , but no on('data') event fired. 我尝试了frame-streamnet.Socket ,但是没有触发on('data')事件。

I use the demo code here, and it works: https://nodejs.org/dist/latest-v7.x/docs/api/net.html#net_net_connect_options_connectlistener 我在这里使用演示代码,并且可以正常工作: https : //nodejs.org/dist/latest-v7.x/docs/api/net.html#net_net_connect_options_connectlistener

Found that I missed the \\r\\n in client.write('{\\"sstation\\":\\"123\\"}\\r\\n') ; 发现,我错过了\\r\\nclient.write('{\\"sstation\\":\\"123\\"}\\r\\n') ; to push message to mina server 将消息推送到Mina服务器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM