【问题标题】:Problems with sending data to remote socket from service从服务向远程套接字发送数据的问题
【发布时间】:2017-06-18 08:01:01
【问题描述】:

我正在使用NotificationListenerService,并且我想在调用onNotificationPosted() 时将数据发送到远程套接字。 但是我有一个套接字已连接的问题,但是当我使用BufferedWriter 或任何其他输出类编写内容时,它永远不会将其发送到远程套接字,直到我关闭应用程序和使用 android studio 的服务。 这是我发送数据的代码:

            new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //     DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                    //    outputStream.writeUTF(send_counter + " $title: " + title + " $mes: " + mes);
                    Log.d(TAG, "started sending info");
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    bw.write(send_counter + " $title: " + title + " $mes: " + mes);
                    bw.newLine();
                    bw.flush();
                //    bw.close();
                    //  outputStream.writeInt(icon.length);
                    //      outputStream.write(icon);
                    Log.d(TAG, "info sent");
                    //    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

只有在我使用 android studio 上的停止按钮完全停止应用程序后,服务器才会从客户端获取消息。 此代码适用于发送消息,因为此代码在主应用程序中对我有用,但只有在后台服务使用它时才会出现问题。

这是我的服务器代码 (c#):

            TcpClient client = server.AcceptTcpClient();
            NetworkStream nwStream = client.GetStream();

            PostToConsole("Phone has connected from: " + ((IPEndPoint)client.Client.RemoteEndPoint).Address + ":" + ((IPEndPoint)client.Client.RemoteEndPoint).Port);

            byte[] buffer = new byte[client.ReceiveBufferSize];
            int res = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            while (res > 0)
            {
                string data = Encoding.UTF8.GetString(buffer, 0, res);
                PostToConsole(data + ((IPEndPoint)client.Client.RemoteEndPoint).Address);

                buffer = new byte[client.ReceiveBufferSize];
                res = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            }
        }

【问题讨论】:

    标签: java c# android sockets


    【解决方案1】:

    尝试创建一个单独的服务类并将数据发送到其中。不要忘记唤醒设备。

    我的意思是,使用startService() 而不是new Thread...

    使用new Thread... 进入一个新的。

    【讨论】:

    • 第一段代码是 NotificationListenerService 中的一个方法。所以你的意思是我应该创建一个新服务来与服务器通信?
    • @EldarAzulay,是的
    • 新服务又出现了同样的问题。我用的是和上面一模一样的代码,只是写在onStart()方法里。
    • @EldarAzulay ,我在您的服务器代码中发现您没有捕获“新行分隔符”
    • @EldarAzulay , stackoverflow.com/q/8387536/1979882 阅读此问题并回答
    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    相关资源
    最近更新 更多