【发布时间】:2017-04-03 13:10:39
【问题描述】:
我正在构建与 android 设备(作为客户端)通信的简单 java 服务器。目前我可以通过蓝牙将消息从我的手机(客户端)发送到我的电脑(服务器)。问题是我无法将消息从服务器发送回客户端。我正在使用蓝洞图书馆。这是我的代码
public class MainTest {
UUID uuid = new UUID("8848",true);
public static void main(String[] args) {
LocalDevice local = null;
try {
local = LocalDevice.getLocalDevice();
} catch (BluetoothStateException e) {
e.printStackTrace();
}
System.out.println("Serverted:\n" +local.getBluetoothAddress() +"\n"+local.getFriendlyName());
MainTest ff = new MainTest();
while (true) {
ff.startserver();
}
}
public void startserver() {
try {
String url = "btspp://localhost:" + uuid + ";name=File Server";
StreamConnectionNotifier service = (StreamConnectionNotifier) Connector.open( url );
StreamConnection con = service.acceptAndOpen();
OutputStream dos = con.openOutputStream();
InputStream dis = con.openInputStream();
while (true) {
byte buffer[] = new byte[1024];
int bytes_read = dis.read( buffer );
String received = new String(buffer, 0, bytes_read);
System.out.println("Message:"+ received);
if("a".equals(received)) {
dos.write("sdfsd".getBytes());
dos.flush();
}
}
// con.close();
} catch ( IOException e ) {
System.err.print(e.toString());
}
}
我也试过用PrintWriter更新代码,但还是没有反应……
public static void startserver() {
try {
String url = "btspp://localhost:" + uuid + ";name=TTT";
StreamConnectionNotifier service = (StreamConnectionNotifier) Connector.open( url );
StreamConnection con = service.acceptAndOpen();
DataOutputStream dos = con.openDataOutputStream();
InputStream dis = con.openInputStream();
PrintWriter pWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(dos)), true);
while (true) {
byte buffer[] = new byte[10];
int bytes_read = dis.read(buffer);
String received = new String(buffer, 0, bytes_read);
System.out.println("Message:"+ received);
pWriter.write("testString");
pWriter.flush();
}
// pWriter.close();
// con.close();
// con.close();
} catch ( IOException e ) {
System.out.println(e.getMessage());
}
}
【问题讨论】:
标签: java bluetooth server outputstream printwriter