简体   繁体   English

保持 Java 蓝牙连接有效

[英]Keeping Java Bluetooth connection alive

I'm building a simple Java Bluetooth server for my computer using the Bluecove API.我正在使用 Bluecove API 为我的计算机构建一个简单的 Java 蓝牙服务器。 I'm building an Android client side app as well but the problem seems to be stemming from the server side app.我也在构建一个 Android 客户端应用程序,但问题似乎源于服务器端应用程序。

I'm sure someone has posted any answer already somewhere and I've tried different solutions rigorously for the past several days and looked at every possible forum but I can't seem to keep the connection on the socket thread alive.我确定有人已经在某处发布了任何答案,过去几天我已经严格尝试了不同的解决方案,并查看了每个可能的论坛,但我似乎无法保持套接字线程上的连接处于活动状态。

I can exchange a message across after a connection is established from android to computer and vice versa from computer to android but immediately after the bytes are exchanged, the Bluecove stack shuts down and closes the socket connection even when I don't explicitly tell it to connection.close().我可以在从 android 到计算机建立连接后交换消息,反之亦然从计算机到 android 但在交换字节后,Bluecove 堆栈立即关闭并关闭套接字连接,即使我没有明确告诉它连接。关闭()。

I've tried to use a while(some statement is true) loop to keep the connection alive and it no longer shuts down the socket after receiving the first message but it can't receive any subsequent messages I send from my smartphone to my computer either.我尝试使用 while(某些语句为真)循环来保持连接处于活动状态,并且在收到第一条消息后不再关闭套接字,但它无法接收我从智能手机发送到计算机的任何后续消息任何一个。 While it is essentially alive, it can't receive any new messages when I try to send them from the smartphone.虽然它本质上是活着的,但当我尝试从智能手机发送它们时,它无法接收任何新消息。 Not sure why.不知道为什么。

I'm sorry, this is my first time posting and I'm not sure why the first part of the code does not display properly on the page.对不起,这是我第一次发帖,我不确定为什么代码的第一部分没有在页面上正确显示。

Code making connection:代码建立连接:

public BluetoothServer() {
    try {
        service = (StreamConnectionNotifier) 
            Connector.open("btspp://localhost:" + new UUID(0x1101).toString() + 
                                ";name=SampleServer");
        
        System.out.println("open connection");

        while (runState == true) {
        
            connection = (StreamConnection) service.acceptAndOpen();
                
            //send a greeting across to android
            outputStream = connection.openOutputStream();
            String greeting = "JSR-82 RFCOMM server says hello";
            outputStream.write(greeting.getBytes());
            
            //run thread that listens for incoming bytes through socket connection
            Thread t = new Thread(new ConnectedThread(connection));
            t.start();                
        }
            
    } catch(IOException e) {}
}

THREAD CODE FOR LISTENING TO INCOMING DATA用于监听传入数据的线程代码

public void run() {
    try {    
        //open input stream to listen to data
        inputStream = connection.openInputStream();              
                                      
        byte buffer[] = new byte[1024];
        int bytes_read = inputStream.read(buffer);

        String received = new String(buffer, 0, bytes_read);
        System.out.println("received: " + received);
            
    } catch(IOException e) {}
}

Unfortunately I can't try your code on my machine in real, but I think I saw your error: in your run()-Method you read from the input stream, print it to the console and then it is over.不幸的是,我无法在我的机器上实际尝试您的代码,但我想我看到了您的错误:在您的 run()-Method 中,您从输入流中读取,将其打印到控制台,然后就结束了。 After your last line在你的最后一行之后

        System.out.println("received: " + received);

your run()-Method is over and the thread is discarded by the runtime.您的 run()-Method 结束,线程被运行时丢弃。 You would need to put the receiving in a while(true) or while(running) loop.您需要将接收放在 while(true) 或 while(running) 循环中。

I modified your code and here it is, however please keep in mind what I said before: I could not test-run it, so it comes totally untested!我修改了你的代码,现在是这样,但是请记住我之前说过的话:我无法测试运行它,所以它完全未经测试!

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;


public class BluetoothServer {

    private boolean runState = true;

    public BluetoothServer(){

        try {
            StreamConnectionNotifier service = (StreamConnectionNotifier) Connector.open("btspp://localhost:" + new UUID(0x1101).toString() + ";name=SampleServer");
            System.out.println("open connection");

            while(runState == true){
                StreamConnection connection = (StreamConnection) service.acceptAndOpen();
                new Listener(connection).start();
            }

        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    private class Listener extends Thread{

        private OutputStream os;
        private InputStream is;

        public Listener(StreamConnection connection){
            try {
                this.os = connection.openOutputStream();
                os.flush();
                this.is = connection.openInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void run(){
            StringBuilder builder;
            try{
                String greeting = "JSR-82 RFCOMM server says hello";
                os.write(greeting.getBytes());

                while(true){
                    builder = new StringBuilder();
                    int tmp = 0;
                    while((tmp = is.read()) != -1){
                        builder.append((char) tmp);
                    }
                    System.out.println("received: " + builder.toString());
                }
            } 
            catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

Here a few general points and thoughts about mine and your code:这里有一些关于我和你的代码的一般观点和想法:

  • As you can see, in the main thread I only accept a new connection.如您所见,在主线程中我只接受一个新连接。 As soon as a client connected, I give the connection object to the thread.一旦客户端连接,我就将连接对象提供给线程。 It then starts to communicate with the client然后它开始与客户端通信
  • In Java, we normally put opening brackets on the same line as the statement which asks for it, but this is just a detail and not a must.在 Java 中,我们通常将左括号与要求它的语句放在同一行,但这只是一个细节而不是必须的。
  • ALLWAYS do something with exceptions or do not catch them.总是做一些有例外的事情,或者不抓住它们。 So the minimum is a printStacktrace() or to declare your method with "throws xException" but do not catch and ignore them.所以最低限度是一个 printStacktrace() 或者用“throws xException”声明你的方法,但不要捕捉和忽略它们。

For the next time you're posting something here, I'd recommend to include all your import statements etc., it can help the people who are trying to help you.下次您在这里发布内容时,我建议包括所有导入语句等,它可以帮助那些试图帮助您的人。 (sometimes, an import can be the cause of all trouble, for example when someone imported java.awt.List instead of java.util.List) (有时,导入可能是所有问题的原因,例如当有人导入 java.awt.List 而不是 java.util.List 时)

I hope that I helped you!我希望我帮助了你!

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

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