蓝牙连接;不能正常发送字符串 [英] Bluetooth-connection; can't send strings properly

查看:388
本文介绍了蓝牙连接;不能正常发送字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的程序的烦恼,当我需要从我的服务器蓝牙插槽字符串发送到我的客户端的蓝牙插座。
一切只要我一次只将一个字符串(例如聊天)工作正常,但如果我需要在短时间内写更多的字符串(以交换信息),该字符串将不会从客户端获取$分开C $℃。例如,如果我要送FirstUser,右后SecondUser客户端不读FirstUser,然后SecondUser。它会读FirstUserSecondUser。我怎样才能避免这种情况?

I have troubles with my program when i need to send Strings from my server bluetooth-socket to my client bluetooth-socket. Everything works fine as long as I am only sending one String at a time (for example chatting) but if I need to write more Strings at a short period of time (to interchange informations), the Strings will not get seperated from the client code. For example if I'm sending "FirstUser" and right after that "SecondUser" the client does not read "FirstUser" and then "SecondUser". It will read "FirstUserSecondUser". How can I avoid this behaviour?

编辑:如果我让线程睡眠之前,它是能够发送一个新的消息,它会读取正确的字符串,但这种方法是不是我需要工作的罚款

If I let the Thread sleep before it is able to send a new message, it reads the right strings but this solution is not working fine for my need.

服务器 - code:发送到所有客户端(编辑)

Server-Code: sending to all clients(edited)

   public synchronized void sendToAll(String message)
{   
    try {
        Thread.sleep(100);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    publishProgress(message);
    for(OutputStream writer:outputList) {
        try {
            writer.write(message.getBytes());
            writer.flush();
        } catch (IOException e) {
            System.out.println("Some-Error-Code");
        }
    }
}

服务器 - code:从客户端阅读:

Server-Code: reading from a client:

   public void run() {
    String nachricht;
    int numRead;
    byte[] buffer = new byte[1024];
    while (runningFlag) 
    {
        try {
            if((numRead = inputStream.read(buffer)) >= 0) { 
                nachricht = new String(buffer, 0, numRead);
                serverThread.handleMessage(nachricht); 
            }
            }
             catch (IOException e) {
                this.cancel();
                e.printStackTrace();
            }
    } 
} 

客户端 - code:从服务器读取(编辑)

Client-Code: reading from server(edited)

@Override
    protected Void doInBackground(Integer... ints) {    
        String nachricht = new String();
        byte[] buffer = new byte[1024];
        int numRead;
        while (runningFlag) 
        {
            try {
                if(((numRead = inputStream.read(buffer)) >= 0)) { 
                    nachricht = new String(buffer, 0, numRead);
                    publishProgress(nachricht);
                }
            }
             catch (IOException e) {
                clientGame.finish();
                e.printStackTrace();
            }                      
        }
        return null;
}

客户端 - code:写入服务器

Client-Code: writing to server

public synchronized void write(String nachricht)
    {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        try {
            outputStream.write(nachricht.getBytes());
            outputStream.flush();
        } catch (IOException e) {
            this.cancel();
            e.printStackTrace();
        }
    }

我AP preciate每一点帮助:)。

I appreciate every little help :) .

推荐答案

您需要封装的数据项,以避免串联。
这意味着你必须写,并继续之前阅读的整体数据项。

You need to encapsulate your data item to avoid concatenation. It means that you have to write and read a whole data item before continuing.

您应该有一些实用方法来做到这一点,而不是直接使用的OutputStream和InputStream的方法:

You should have some utility methods to do that instead of directly using methods of OutputStream and InputStream :

public static void writeItem(OutputStream out, String s) throws IOException
{
    // Get the array of bytes for the string item:
    byte[] bs = s.getBytes(); // as bytes
    // Encapsulate by sending first the total length on 4 bytes :
    //   - bits 7..0 of length
    out.write(bs.length);      // modulo 256 done by write method
    //   - bits 15..8 of length
    out.write(bs.length>>>8);  // modulo 256 done by write method
    //   - bits 23..16 of length
    out.write(bs.length>>>16); // modulo 256 done by write method
    //   - bits 31..24 of length
    out.write(bs.length>>>24); // modulo 256 done by write method
    // Write the array content now:
    out.write(bs); // Send the bytes
    out.flush();
}

public static String readItem(InputStream in) throws IOException
{
    // first, read the total length on 4 bytes
    //  - if first byte is missing, end of stream reached
    int len = in.read(); // 1 byte
    if (len<0) throw new IOException("end of stream");
    //  - the other 3 bytes of length are mandatory
    for(int i=1;i<4;i++) // need 3 more bytes:
    {
        int n = in.read();
        if (n<0) throw new IOException("partial data");
        len |= n << (i<<3); // shift by 8,16,24
    }
    // Create the array to receive len bytes:
    byte[] bs = new byte[len];
    // Read the len bytes into the created array
    int ofs = 0;
    while (len>0) // while there is some byte to read
    {
        int n = in.read(bs, ofs, len); // number of bytes actually read
        if (n<0) throw new IOException("partial data");
        ofs += n; // update offset
        len -= n; // update remaining number of bytes to read
    }
    // Transform bytes into String item:
    return new String(bs);
}

然后你同时使用服务器和放这些方法;客户端读取和写入您的字符串项目。

Then you use these methods both for server & client to read and write your String items.

这篇关于蓝牙连接;不能正常发送字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆