【问题标题】:Websocket Server as Service on Android TabletAndroid 平板电脑上的 Websocket 服务器即服务
【发布时间】:2014-12-01 15:31:07
【问题描述】:

我有以下情况。 一个 Websocket 服务器,作为后台服务在 Android 平板电脑上运行。 该服务还启动 Websocket 客户端,在服务器启动后处理应用内通信。我在一个单独的项目中还有一个 java web-socket 客户端来连接服务器并与之通信。

这一切都很好,只要我不尝试将 WebSocket 服务器实现为服务。 我可以像没有明天一样连接和发送数据。

但是,一旦我将 Websocket 服务器作为服务运行,我就无法再连接到它。既不是我的“inAppClient”,也不是我单独的 java 客户端。

我在清单中设置了互联网的权限,并尝试了不同的端口。我还使用 adb forward tcp:38301 tcp:38301 进行端口转发

当我尝试使用应用内客户端连接到服务器时出现以下错误: E/WSCLient:错误未能连接到/127.0.0.1(端口38301):连接失败:ECONNREFUSED(连接被拒绝)

我也尝试使用 localhost 而不是 127.0.0.1。

这是我的服务器的源代码:

private class WSServer extends WebSocketServer{
        private static final String TAG = "WSServer";
//      private static final int TIMEOUT = 60;
        private int port = 38301;
        private int testLevel = Constants.BOUNCE_MESSAGES;

        public WSServer( InetSocketAddress address ) {
            super( address );
            Log.d(TAG, "creating instance of local WSServer");
            wsClient = new WSClient(port);
        }

        public WSServer(int port)
        {
            super( new InetSocketAddress( port ) );
            Log.d(TAG, "creating instance of local WSServer on port " + port);
            wsClient = new WSClient(port);
        }

        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            Log.d(TAG, "connection Details: " + conn.getLocalSocketAddress() + "; " + conn.getRemoteSocketAddress());
            Log.d(TAG, "Connection successfully opened on port: " + this.getPort());
        }

        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            Log.d(TAG, "Connection closed");
        }

        @Override
        public void onMessage(WebSocket conn, String message) {
            Log.d(TAG, "Received Message: " + message);
            if(testLevel == Constants.BOUNCE_MESSAGES)
            {
                conn.send(new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date()) + ": " + message);
            }
        }

//      @Override
//      public void onFragment( WebSocket conn, Framedata fragment ) {
//          System.out.println( "received fragment: " + fragment );
//      }

        @Override
        public void onError(WebSocket conn, Exception ex) {
            Log.d(TAG, "onError()", ex);
        }
}

这是我的服务的源代码:

public CommManager(){
        wsServer = new WSServer(port);
        Log.d(TAG, "Server Adress: " + wsServer.getAddress());
    }

    public CommManager(int port){
        this.port = port;
        Log.d(TAG, "CommManager is starting");
        wsServer = new WSServer(port);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle extras = intent.getExtras();
        if(extras == null) {
            Log.d(TAG, "Port wurde nicht gesetzt. Default Port " + port + " wird verwendet");
        }
        else {
            port = (Integer)extras.get("port");
        }

        return startMode;
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "Binding Service to Activity");
        return commManagerBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {

        return allowRebind;
    }

最后但并非最不重要的是我的应用内客户端:

private class WSClient {

        public String message;
        private static final String TAG = "WSCLient";

        private WebSocketClient mWebSocketClient;
        private int port = 38301;

        public WSClient(){
            connectWebSocket();
        }
        public WSClient(int port) {
            Log.d(TAG, "starting local WSClient");
            if(port != 0){
                this.port = port;
            }
            connectWebSocket();
        }

        private void connectWebSocket() {
            Log.d(TAG, "establishing Connection to local WSServer");
            URI uri;
            try {
                uri = new URI("ws://localhost:" + port);
            } catch (URISyntaxException e) {
                Log.e(TAG, "uri-error: " + "ws://localhost:" + port);
                e.printStackTrace();
                return;
            }

            mWebSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    Log.d(TAG, "Opened");
                    mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
                }

                @Override
                public void onMessage(String s) {
                    Log.d(TAG, "received Message: " + s);
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    Log.d(TAG, "Closed " + s);
                }

                @Override
                public void onError(Exception e) {
                    Log.e(TAG, "Error " + e.getMessage());
                }
            };
            mWebSocketClient.connect();
        }

        public void sendMessage(String message) {

            if(mWebSocketClient != null) {
                mWebSocketClient.send(message);
            }
            else {
                Log.e(TAG, "No WebSocketClient available. Trying to reconnect and create new Client instance");
                connectWebSocket();
            }
        }

    }

我不知道为什么我无法与我的服务器建立连接。 希望您能提供帮助。

【问题讨论】:

标签: java android service websocket server


【解决方案1】:

所以我通过改变我的实现方式解决了这个问题。我对 Server 和 Client 类进行了子类化,然后它就起作用了。 :)

【讨论】:

  • 你能分享你的完整代码吗?我正在实施类似的服务。
  • 抱歉,由于我更换了员工,我无法再访问该代码
  • @Chao 如果你还在寻找一些代码,this post 有一些细节。
猜你喜欢
  • 2017-09-27
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多