-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleSPPServer.java
More file actions
86 lines (67 loc) · 2.54 KB
/
SimpleSPPServer.java
File metadata and controls
86 lines (67 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package mypkg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.bluetooth.*;
import javax.microedition.io.*;
/**
* Class that implements an SPP Server which accepts single line of message from
* an SPP client and sends a single line of response to the client.
*/
public class SimpleSPPServer {
// start server
private void startServer() throws IOException {
// Create a UUID for SPP
UUID uuid = new UUID("1101", true);
// Create the servicve url
String connectionString = "btspp://localhost:" + uuid + ";name=Sample SPP Server";
// open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector
.open(connectionString);
// Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection = streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: " + dev.getBluetoothAddress());
System.out.println("Remote device name: " + dev.getFriendlyName(true));
// read string from spp client
InputStream inStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String lineRead = bReader.readLine();
System.out.println(lineRead);
// send response to spp client
OutputStream outStream = connection.openOutputStream();
PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(outStream));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String sendStr = "";
char cbuf[] = new char[255];
while (!(sendStr.equalsIgnoreCase("exit"))) {
if(br.ready()){
sendStr = br.readLine();
pWriter.write(sendStr + "\n");
pWriter.flush();
System.out.println("Sent text\n");
}
if(bReader.ready()){
bReader.read(cbuf);
System.out.println(cbuf);
sendStr = cbuf.toString();
for(int i = 0; i < cbuf.length; i++)
cbuf[i] = 0;
}
}
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
// display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: " + localDevice.getBluetoothAddress());
System.out.println("Name: " + localDevice.getFriendlyName());
SimpleSPPServer sampleSPPServer = new SimpleSPPServer();
sampleSPPServer.startServer();
}
}