I am developing a BluetoothServer using Raspberry, bluecove-2.1.0.jar
java version "1.8.0_06"
Java(TM) SE Runtime Environment (build 1.8.0_06-b23)
Java HotSpot(TM) Client VM (build 25.6-b23, mixed mode)
Here the server java code:
public class BluetoothServer extends Thread {
UUID uuid = new UUID("0000110100001000800000805F9B34FB", false); // This is a magic number
String url = "btspp://localhost:" + uuid.toString() + ";name=xxxx";
Security security = new Security();
/** Constructor */
public BluetoothServer() {
}
#Override
public void run() {
waitForConnection();
}
/** Waiting for connection from devices */
private void waitForConnection() {
// retrieve the local Bluetooth device object
LocalDevice local = null;
StreamConnectionNotifier notifier = null;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC); // generally discoverable, discoveryTimeout should be disabled - but isn't.
notifier = (StreamConnectionNotifier) Connector.open(url);
// Bluetooth may go undiscoverable after 180sec default discoveryTimeout, so reset it on separate thread every 179sec.
new Timer().schedule(new TimerTask(){
#Override
public void run() {
try {
LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
System.out.println("TimerTask exception: " + e.getMessage());
e.printStackTrace();
}
}
}, 0, 179000);
} catch (Exception e) {
System.out.println("Server exception: " + e.getMessage());
e.printStackTrace();
}
// waiting for connection
while (true) {
try {
System.out.println("waiting for connection...");
connection = notifier.acceptAndOpen();
Thread processThread = new Thread(new ProcessConnectionThread(
connection, this));
processThread.start();
System.out.println("processThread.started...");
// bluetooth may have been set undiscoverable after connection
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (Exception e) {
System.out.println("Server exception: " + e.getMessage());
e.printStackTrace();
return;
}
}
}
public static void main(String[] args) {
System.out.println("Server startup now");
new BluetoothServer().start();
}
public Security getSecurity() {
return security;
}
}
When I Start the server on the command line:
sudo java -cp /jars:/jars/bluetoothserver.jar:/jars/bluecove-2.1.0.jar:/jars/pi4j-core.jar com.bluetoothserver.BluetoothServer
I get this error:
BlueCove version 2.1.0 on bluez
Server exception: The connection implementation for btspp cannot be found.
javax.microedition.io.ConnectionNotFoundException: The connection implementation for btspp cannot be found.
at javax.microedition.io.Connector.open(Connector.java:238)
at javax.microedition.io.Connector.open(Connector.java:181)
at javax.microedition.io.Connector.open(Connector.java:162)
at com.bluetoothserver.BluetoothServer.waitForConnection(BluetoothServer.java:56)
at com.bluetoothserver.BluetoothServer.run(BluetoothServer.java:32)
waiting for connection...
Server exception: null
java.lang.NullPointerException
at com.bluetoothserver.BluetoothServer.waitForConnection(BluetoothServer.java:87)
at com.bluetoothserver.BluetoothServer.run(BluetoothServer.java:32)
Any ideas ? Thanks
Had the same issue.
JDK 1.8.0_06 has the implementation of javax.microedition.io.Connector in it's rt.jar. In my case the solution was to remove javax.microedition package from rt.jar to use BlueCove implementation.
Related
I want to create communication android app using tcp server-client. I am using android phone as server and linux pc as client, I have created application on linux which works as client.When I Try to create server, it stuck at serversocket.accept(). So client is not able to connect server. I am using following code for server creation
class Thread1 implements Runnable {
int dsport = 48618
#Override
public void run() {
try {
server_socket = new ServerSocket(dsport);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = server_socket.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And I am using qt creator on client side
void run()
{
Qstring iplist;
QList<QHostAddress> ipadd = QNetworkInterface::allAddress();
socket = new QTcpSocket(this);
connect(socket,SIGNAL(connected()),this,SLOT(newConnection)));
socket->connectToHost(ipadd.at(0),48618);
}
void newConnection()
{
qDebug()<<"socket connected";
}
here ipadd.at(0) gives me local host address. Is there any issue with port I am using? if yes then how to get reliable port for server creation.
How can I resolve this issue ?
I am currently in the process of writing an app which has the phone connect to a server.
Both client and server are using the Kryonet framework.
The problem ist the following :
When the server is running and I then start up the client, the client immediately disconnects from the server but the Programm itself keeps running so it is only possible that the client Thread died for whatever reason.
I am using kryonet-2.21 on both server and client.
I tried my code on Android aswell as on pc.
I also tried to troubleshoot everything I could and tried everything I found searching for my problem.
The Client code :
public class LogicHandler extends Thread {
private Client client;
public LogicHandler() {
}
public Client getClient() {
return client;
}
public void run() {
client = new Client(33554432, 33554432);
new Thread(client).start();
try {
getClient().connect(5000, "localhost", 54555, 54777);
} catch (IOException e) {
e.printStackTrace();
}
Packets.register(getClient());
getClient().addListener(new Listener() {
public void received(Connection connection, Object object) {
System.out.println("received " + object);
if (object instanceof ConnectionResponse) {
}
if (object instanceof ScheduleResponse) {
}
}
public void disconnected(Connection connection) {
}
});
getClient().sendTCP(new ConnectionRequest());
}
public static void main(String[] args) {
new LogicHandler().start();
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("wait");
}
}
}
The Server code :
public class ServerLogicHandler {
private Server server;
private List<Client> clients;
private List<Connection> connections;
public ServerLogicHandler() {
System.out.println("Server is starting!");
server = new Server(33554432, 33554432);
server.start();
try {
server.bind(54555, 54777);
} catch (Exception e) {
server.stop();
System.out.println("Port belegt. Server wird gestoppt!");
System.exit(0);
}
Packets.register(server);
clients = new ArrayList<Client>();
connections = new ArrayList<Connection>();
server.addListener(new Listener() {
public void received(Connection connection, Object object) {
System.out.println("got packet");
if (object instanceof ConnectionRequest) {
System.out.println("size " + connection.sendTCP(new ScheduleResponse()));
}
}
public void disconnected(Connection connection) {
System.out.println("Disco " + connection.getID());
}
public void connected(Connection connection) {
System.out.println(connection.getRemoteAddressTCP().getPort() + " "
+ connection.getRemoteAddressTCP().getAddress());
}
});
System.out.println("Server started!");
}
public Server getServer() {
return server;
}
public static void main(String... args) {
new ServerLogicHandler();
}
}
The client doesn't output anything apart from the 'wait' every second. This means that either the server didn't send any packet or the client closed already. My guess is that the latter happened because the server outputs the following :
Server is starting!
Server started!
54408 /127.0.0.1
Disco 1
When I start a new client the last 2 lines would just repeat e.g. '54890 /127.0.0.1
Disco 2
'
From this I guess that the client closes for whatever reason before even sending any packets. None of my Google searches brang up any success.
I created a simple Client-Server Application, which is working fine.
The server is listening to a port and then starts a thread for the job.
At the moment the only way (outside the IDE) is, to kill the java.exe to stop the server.
Both example classes are very stripped-down.
Main Class:
public static void main(String[] args) {
MultiThreadedServer server = new MultiThreadedServer(9000);
new Thread(server).start();
}
MultiThreadedServer Class:
public class MultiThreadedServer implements Runnable {
protected int serverPort = 9000;
protected ServerSocket serverSocket = null;
protected Thread runningThread = null;
protected ExecutorService threadPool = Executors.newFixedThreadPool(Options.getInstance().getThreadCount());
public MultiThreadedServer(int port) {
this.serverPort = port;
}
public void run() {
synchronized (this) {
this.runningThread = Thread.currentThread();
}
openServerSocket();
while (true) {
Socket clientSocket;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
throw new RuntimeException("Error accepting client connection", e);
}
try {
this.threadPool.execute(new WorkerRunnable(clientSocket, Constants.appName + " Thread"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port " + serverPort, e);
}
}
}
I am wondering, what is the best practice to start the server application?
I have solved it on my own.
I´ve created a windows batch script, which processes some pre-requirements and starts the server application.
And with nssm nssm I have installed this batch file as windows service. Not the server application is controllable by windows services.
I am currently trying to grab the basics of RMI by implementing a Server/Client Structure where both the Client can invoke remote Operations on the Server, and the Server can invoke Client functions:
public class Client extends GenericRMI implements ClientInterface {
public ServerInterface server;
public Client() {
try {
String IP = InetAddress.getLocalHost().getHostAddress();
server = (ServerInterface) Naming.lookup("//192.168.2.124/WServer");
int uniqueID = (int) Math.round(Math.random() * 1000);
super.setUpRMI("WClient" + IP + "_" + uniqueID);
server.registerNewClient(IP, uniqueID);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setUserID(int id) {
System.out.println("got my ID from the server: " + id);
}
}
public class Server extends GenericRMI implements ServerInterface {
private List<ClientInterface> clients;
public Server() {
clients = new ArrayList<ClientInterface>();
super.setUpRMI("WServer");
}
public void registerNewClient(String IP, int uID) throws RemoteException {
try {
ClientInterface c = (ClientInterface) Naming.lookup("//" + IP + "/WClient" + IP + "_"
+ uID);
int newID = clients.size();
clients.add(c);
c.setUserID(newID);
} catch (Exception e) {
e.printStackTrace();
}
}
}
and, in the main function:
new Server();
Thread.sleep(1000);
new Client();
Thread.sleep(1000);
new Client();
Thread.sleep(1000);
new Client();
interfaces are defined by
public interface ServerInterface extends Remote...
RMI setup
public class GenericRMI implements Remote, Serializable {
protected Registry registry;
public void setUpRMI(String bindName) {
if (registry == null) {
try {
registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
} catch (ExportException e) {
// client and server on one PC
} catch (RemoteException e) {
e.printStackTrace();
}
}
try {
Naming.rebind(bindName, this);
} catch (RemoteException | MalformedURLException e) {
e.printStackTrace();
}
System.out.println("Started " + bindName);
}
}
however, output is like
Started WServer
Started WClient192.168.2.124_501
got my ID from the server: 0
Started WClient192.168.2.124_655
got my ID from the server: 0
Started WClient192.168.2.124_771
got my ID from the server: 0
even if i debug it, the server has a different ID for each client. I guess I am doing a terrible mistake somewhere, since I used to think that the server would only have ONE instance running. How can I achieve that?
EDIT
the Problem is; if i debug the registerNewClient() function, the respective Server object changes for each Client:
Server#7728992
Server#5fbb71ac
...
Even if i make the clients' list synchronized, it doesn't help. However, making the clients field transient server-side leads to a null pointer exception on it, indicating that it indeed is a new instance.
You do have only one instance running. You only called new Server() once, and in any case there's no way three instances can be bound to the same name in the Registry. More likely you have a concurrency problem on the unsynchronized 'clients' collection.
I'm developing a J2ME program with eclipse / WTK 2.5.2 and having problem with connecting two emulators using bluetooth. There is one server and one .client running on two different emulators.
The problem is client program cannot discover any bluetooth device. Here is the server and client codes:
public Server()
{
try
{
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
server = (StreamConnectionNotifier)
Connector.open("btspp://localhost:"
+ UUID_STRING + ";name=" + SERVICE_NAME);
Util.Log("EchoServer() Server connector open!");
}
catch (Exception e)
{}
}
after calling Connector.open, I get following warning in console, which i believe is related:
Warning: Unregistered device: unspecified
and client code that searches for devices:
public SearchForDevices(String uuid, String nm)
{
UUIDStr = uuid;
srchServiceName = nm;
try
{
LocalDevice local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
deviceList = new Vector();
agent.startInquiry(DiscoveryAgent.GIAC, this); // non-blocking
}
catch (Exception e)
{}
}
system never calls deviceDiscovered, but calls inquiryCompleted() with INQUIRY_COMPLETED parameter, so I suppose client program runs fine.
Bluetooth is enabled at emulator settings..
I tested almost same code from NetBeans IDE 6.8 with WTK 2.5.2_01 emulator and it works well. (I mean it discovered device)
public void startBTServer() {
try
{
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
StreamConnectionNotifier server = (StreamConnectionNotifier)
Connector.open("btspp://localhost:F0E0D0C0B0A000908070605040302010"
+ ";name=" + ";test");
}
catch (Exception e)
{}
}
public void startBTClient() {
String UUIDStr = "F0E0D0C0B0A000908070605040302010";
try
{
LocalDevice local = LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
agent.startInquiry(DiscoveryAgent.GIAC, (DiscoveryListener) this);
}
catch (Exception e)
{}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
System.out.println("device discovered:" + btDevice.toString());
}
This code print out the below log:
From server:
Running in the identified_third_party security domain
Device Bluetooth Address: 0000000DECAF
From client:
Device Bluetooth Address: 0123456789AF
device discovered:RemoteDevice[address=0000000DECAF, name=null, encrypted=false, authenticated=false]