java - 使用来自蓝牙连接的传入数据来处理特定对象? C# Windows 窗体应用程序和 Java Android 应用程序

标签 java c# android bluetooth

第一篇文章在这里。我试图寻找一个我有的问题,但没有成功,所以我想我自己问。

我正在开发 2 个程序。 Java 中的 Android 应用程序和 Windows 上的 C# Windows 窗体应用程序。它们都是简单的记分计算器,用于记录 2 位玩家的得分。

这两个程序的目标是使用蓝牙连接在彼此之间来回发送数据,以便它们“同步”。 Android 应用程序是客户端,C# 应用程序是服务器(32feet 库)。

使用 Android 上的蓝牙聊天示例和我在 VS 中组合的一些代码,我成功地让 2 个程序相互连接并发送和接收数据,太棒了!

但现在我的主要目标是我需要找到一种方法来获取来自 Android 应用程序的传入数据并更改 Windows 应用程序上的适当标签/文本。

例如:

  • 在 Windows 应用程序上,有 2 个标签:一个用于玩家 1,一个用于玩家 2,两者都显示“10”。
  • 在 Android 应用中,我有 2 个按钮,分别从玩家 1 或玩家 2 的得分中减去。
  • 在 Android 应用程序上,如果我触摸从 Player1 中减去 (-) 1 的按钮,则结果将为 9。我现在希望将该更改应用于 Windows 应用程序上的 Player1 分数标签,它也会显示 9。
  • 然后我希望玩家 2 的得分也得到同样的结果。

这是我能描述的最好的目标,我想知道这是否可能,如果可以,请指出正确的方向。

这里是我到目前为止所提供的一些代码:

C# Windows 窗体应用程序:

private void button1_Click(object sender, EventArgs e)
        {
            if (serverStarted == true)
            {
                updateUI("Server already started");
                return;
            }
            if (radioButton1.Checked)
            {
                connectAsClient();
            }
            else
            {
                connectAsServer();
            }
        }

        private void connectAsServer()
        {
            Thread bluetoothServerThread = new Thread(new ThreadStart(ServerConnectThread)); //creates new thread and runs "ServerConnectThread"
            bluetoothServerThread.Start();
        }

        private void connectAsClient()
        {
            throw new NotImplementedException();
        }

        Guid mUUID = new Guid("fa87c0d0-afac-11de-8a39-0800200c9a66");
        bool serverStarted = false;


        public void ServerConnectThread()
        {
            serverStarted = true;
            updateUI("Server started, waiting for client");
            BluetoothListener blueListener = new BluetoothListener(mUUID);
            blueListener.Start();
            BluetoothClient conn = blueListener.AcceptBluetoothClient();
            updateUI("Client has connected");

            Stream mStream = conn.GetStream();

            while (true)
            {

                try
                {
                    //handle server connection
                    byte[] received = new byte[1024];
                    mStream.Read(received, 0, received.Length);
                    updateUI("Received: " + Encoding.ASCII.GetString(received));
                    byte[] sent = Encoding.ASCII.GetBytes("hello world");
                    mStream.Write(sent, 0, sent.Length);
                }
                catch (IOException exception)
                {
                    updateUI("Client disconnected");
                }
            }
        }

        private void updateUI(string message)
        {
            Func<int> del = delegate ()
            {
                textBox1.AppendText(message + Environment.NewLine);
                return 0;

            };
            Invoke(del);
        }

    }

Android 应用程序(蓝牙聊天示例的 fragment - 我认为这是唯一相关的部分):

    /**
     * Sends a message.
     *
     * @param message A string of text to send.
     */
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            mOutEditText.setText(mOutStringBuffer);
        }
    }

最佳答案

您需要将客户端添加到流列表中以供引用,并将每个客户端的分数存储在列表中,然后将来自每个客户端的数据发送到其余客户端 所以从服务器上你基本上会得到这样的东西

List<Stream> clients=new List<Stream>();
List<String> client_scores=new List<String>();
    public void ServerConnectThread()
    {
        serverStarted = true;
        updateUI("Server started, waiting for client");
        BluetoothListener blueListener = new BluetoothListener(mUUID);
        blueListener.Start();
        BluetoothClient conn = blueListener.AcceptBluetoothClient();
        updateUI("Client has connected");

        Stream mStream = conn.GetStream();
    clients.add(mStream);
    client_scores.add(new Random().Next()+"");
    int index_cnt = clients.IndexOf(mStream);

        while (true)
        {

            try
            {
                //handle server connection
                byte[] received = new byte[1024];
                mStream.Read(received, 0, received.Length);

                updateUI("Received: " + Encoding.ASCII.GetString(received));
                client_scores[client_scores.FindIndex(ind=>ind.Equals(index_cnt))]       =  Encoding.ASCII.GetString(received);
                byte[] sent = Encoding.ASCII.GetBytes("hello world");
                mStream.Write(sent, 0, sent.Length);
                foreach(Stream str in clients)
                {
                 byte[] my_score = Encoding.ASCII.GetBytes(clients.ToArray()[index_cnt]+"");
                str.Write(my_score, 0, my_score.Length);
                }
            }
            catch (IOException exception)
            {
                updateUI("Client disconnected");
            }
        }
    }

然后,您可以序列化以某种 json 形式发送的数据,以便轻松发送多个数据字段,例如:

{
  "data type": "score",
  "source_id": "client_unique_id",
  "data": "200"
}

在显示端,只需获取(在我们的示例中为 source_id 和数据)的值并显示在标签上

关于java - 使用来自蓝牙连接的传入数据来处理特定对象? C# Windows 窗体应用程序和 Java Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62378338/

相关文章:

c# - 如何在 ASP.NET Core 2.2 中创建角色并将其分配给用户

java - 使用 MrUnit 对 Mongo-Hadoop 作业进行单元测试

java - 使用 LWUIT 列出带复选框的列表

java - 如何使用 Java Spring 从缓存中删除特定键

java - GWT 中调整面板大小的触摸事件

c# - 如何使用 TPL 数据流库指定无序执行 block ?

c# - 在抛出未处理的 JavaScript 错误之前,不查询 IServiceProvider IElementBehaviorFactory

java - Mac OSX 上的 Android Studio 模拟器 (AVD) : AVD icon quickly appears and immediately disappears

android - 在Android中获取Scrollview中ImageView的id

android - 我想在 android 中裁剪图像时修复矩形大小