📄 echoserver.java
字号:
import javax.bluetooth.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class EchoServer implements Runnable {
StreamConnectionNotifier notifier;
StreamConnection conn;
LocalDevice localDevice;
ServiceRecord serviceRecord;
InputStream input;
OutputStream output;
private boolean isInit;
private static String serverUrl = "btspp://localhost:" + BluetoothEchoDemo.RFCOMM_UUID + ";name=rfcommtest;authorize=true";
public EchoServer() {
isInit = false;
Thread thread = new Thread(this); thread.start();
}
public void run() {
if (!isInit) {
// Initialization is done in the thread to avoid dead lock 'isInit' ensures it is done once only
try {
conn = null;
localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable( DiscoveryAgent.GIAC );
notifier = (StreamConnectionNotifier)Connector.open(serverUrl);
} catch (BluetoothStateException e) {
System.err.println( "BluetoothStateException: " + e.getMessage() );
} catch (IOException e) {
System.err.println( "IOException: " + e.getMessage() );
}
isInit=true;
System.out.println( "Starting Echo Server" );
}
//
try {
System.out.println("\n\nServer Running...");
// Pauses thread until Transmission occurs
conn = notifier.acceptAndOpen();
// Read Data Transmission
String msg = BluetoothEchoDemo.readData(conn);
System.out.println("Received Message from Client: " + msg);
// Send Back a Message
msg = "Hello Back from Server";
output = conn.openOutputStream();
output.write(msg.length()); // length is 1 byte output.write(msg.getBytes()); output.close();
} catch (Exception ex) {
System.err.println("Bluetooth Server Running Error: " + ex);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -