Websocket服务器作为Android平板电脑上的服务

时间:2014-12-01 15:31:08

标签: java android service websocket server

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

这一切都运行正常,只要我不尝试将WebSocket服务器实现为服务。 我可以连接并发送数据,就像没有明天一样。

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

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

进行portforwarding

当我尝试使用我的应用内客户端连接到服务器时出现的错误如下: 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();
            }
        }

    }

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

1 个答案:

答案 0 :(得分:0)

所以我只是改变了我的实现方式来解决问题。我将服务器和客户端类子类化,然后它工作。 :)