【发布时间】:2012-02-03 19:49:33
【问题描述】:
当我需要将字符串从服务器蓝牙套接字发送到客户端蓝牙套接字时,我的程序出现问题。 只要我一次只发送一个字符串(例如聊天),一切正常,但如果我需要在短时间内编写更多字符串(交换信息),字符串将不会与客户端代码分离.例如,如果我正在发送“FirstUser”并且在“SecondUser”之后,客户端不会读取“FirstUser”然后是“SecondUser”。它将读取“FirstUserSecondUser”。如何避免这种行为?
编辑:如果我让线程在能够发送新消息之前休眠,它会读取正确的字符串,但这个解决方案不能满足我的需要。
服务器代码:发送到所有客户端(已编辑)
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");
}
}
}
服务器代码:从客户端读取:
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();
}
}
}
客户端代码:从服务器读取(已编辑)
@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;
}
客户端代码:写入服务器
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();
}
}
感谢每一个小小的帮助:)。
【问题讨论】:
-
您的服务器是否向客户端发送消息,反之亦然?
-
双向循环。在客户端或服务器能够发送另一个字符串之前,我暂时“解决”了 Thread.sleep(100) 的问题。但这并不是一个很好的解决方案。
-
您是否正在刷新所有已发送的消息?
-
是的,我愿意。似乎它写入消息的速度如此之快,以至于 read() 函数只能看到一个传入的字符串。
-
它不是人,而是机器。没有什么叫“这么快”。到目前为止,我无法帮助您提供您提供的信息。研究流是如何工作的,并确保你正在冲洗所有东西。也许,也可以发布更多代码。
标签: java android bluetooth inputstream outputstream