I am making a bluetooth related application to browse the internet.. With Server as laptop/desktop and client as the mobile phone.. i need to establish a connection between client and server.. but the execution of the server suddenly stops at the method acceptAndOpen() .. Please help to solve the problem.. this is the code where it stops in the server side:
while (mServerState) {
StreamConnection btConn = null;
try {
updateStatus("[server:] Now waiting for a client to connect");
//here is the error
btConn = (StreamConnection) btServerNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(btConn);
System.out.println("Remote device address: " + dev.getBluetoothAddress());
updateStatus("Remote device " + dev.getFriendlyName(true) + "connected");
} catch (IOException ioe) {
}
if (btConn != null) {
processConnection(btConn);
}
}
Related
I am trying to make connection between multiple device one act as server or group owner and other as client, which I have implemented using wifi direct and wifi p2p and working fine.
After device connected in a group, i am trying to make socket connection between the server and multiple clients but I can't connect using socket. showing below error
java.net.ConnectException: failed to connect to /192.168.49.1 (port 8988) after 5000ms: isConnected failed: ECONNREFUSED (Connection refused)
SockertServer code
#Override
protected Object doInBackground(Object[] params) {
try {
server = new ServerSocket(8988);
Log.d("ServerActivity", "Server: Socket opened");
Log.d("ServerActivity", server.getLocalPort() + "");
Log.d("ServerActivity", server.getInetAddress() + "");
Socket client = server.accept();
Log.d("ServerActivity", "Server: connection done");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
client.getOutputStream()
);
objectOutputStream.writeObject("Hie");
client.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Client Socket
#Override
protected Object doInBackground(Object[] params) {
try {
mSocket = new Socket();
mSocket.bind(null);
mSocket.connect((new InetSocketAddress(getAddr, portNo)), SOCKET_TIMEOUT);
if (mSocket.isConnected()) {
Log.d("Client Activity", "Socket Connected Successfully");
} else {
Log.d("Client Activity", "Socket not Connected ");
}
ObjectInputStream objectOutputStream = new
ObjectInputStream(mSocket.getInputStream());
msg = (String) objectOutputStream.readObject();
message.onMessageSend(msg);
Log.e(".......................", "Message" + msg);
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (mSocket != null) {
if (mSocket.isConnected()) {
try {
mSocket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
return msg;
}
So anyone can help me out with this problem.Thanks in advance!!
ECONNREFUSED means that the connection was attempted and the remote host port is not listening. Hence this can be caused because of:
Is it a valid IP? check using ifconfig or ipconfig. you can try pinging the server.
It may also be due to the following reasons:
-The server couldn't send a response: Ensure that the backend is working properly at IP and port mentioned.
-SSL connections are being blocked.
-Request timeout: Change request timeout
I have a java application which uses jsmpp library to send SMSs to SMSC. Application connects successfully and sends SMSs. Connection issue occurs after a week or so up time, during this up time it sends thousands of SMSs. But suddenly after few days application starts facing connection issues, some time 'Negative bind response 0x00045' and some time waiting bind response. When I check from wireshark, Application constantly sends enquire line packets and receives responses for them with status 'OK'. This means that application is connected but still it is attempting for new connection. Below is code for connection management.
I call newSession method to get session for SMS sending..
private SMPPSession newSession(BindParameter bindParam) {
SMPPSession tmpSession = null;
dbOperations = new DBOperations();
Settings settings = dbOperations.getSettings();
if (settings == null)
logger.error("ERROR: No settings found to connect to SMSC!");
else {
try {
tmpSession = new SMPPSession(remoteIpAddress, remotePort, bindParam);
tmpSession.addSessionStateListener(new MySessionStateListener());
tmpSession.setMessageReceiverListener(new DeliverReceiptListener());
tmpSession.setEnquireLinkTimer(50000);
tmpSession.setTransactionTimer(5000L);
logger.info("New session established with " + remoteIpAddress + " on port " + remotePort + " as Transmitter");
} catch (Exception er) {
gateway=null;
logger.error("Exception Occurred While making Connection with SMPP Server with IP: " + remoteIpAddress + " and port " + remotePort+" and Error is:"+er.getMessage());
}
}
return tmpSession;
}
public void reconnectAfter(final long timeInMillis) {
final Settings settings = dbOperations.getSettings();
if (settings == null) {
logger.error("No settings found to connect to SMSC!");
return;
}
new Thread() {
#Override
public void run() {
logger.info("Schedule reconnect after " + timeInMillis + " milliseconds");
try {
Thread.sleep(timeInMillis);
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
int attempt = 0;
while (session == null || session.getSessionState().equals(SessionState.CLOSED)) {
try {
logger.info("Reconnecting attempt #" + (++attempt) + "...");
session = newSession(bindParam);
} catch (Exception e) {
logger.error("Failed opening Transmitter connection and bind to " + remoteIpAddress + ":" + remotePort + " ");
logger.error(e.getMessage());
// wait for a second
try {
Thread.sleep(reconnectInterval);
} catch (InterruptedException ee) {
logger.error(e.getMessage());
}
}
}
}
}.start();
}
private class MySessionStateListener implements SessionStateListener {
public void onStateChange(SessionState newState, SessionState oldState, Object o) {
if (newState.equals(SessionState.OPEN)) {
logger.info("TCP connection established with SMSC at address " + remoteIpAddress);
}
if (newState.equals(SessionState.BOUND_TRX)) {
logger.info("SMPP Transceiver connection established with SMSC at address " + remoteIpAddress + " and port " + remotePort);
}
if (newState.equals(SessionState.CLOSED) || newState.equals(SessionState.UNBOUND)) {
logger.error("Connection closed, either by SMSC or there is network problem");
if(newState.equals(SessionState.CLOSED))
logger.error("Connection closed");
else
logger.error("Connection unbound");
logger.info("Reconnecting.......");
reconnectAfter(reconnectInterval);
}
}
}
I don't why this code retries for fresh connection when it is already connected. Any clue is appreciated.
It seems the session still valid.
Make sure there are no zombie session, if there are any then close them all. It make sure the enquire link sending stop.
I'm writing an application to communicate between my smartphone and a computer using a bluetooth device.
I'm using Bluecove to manage the bluetooth on the computer, and the android API for my android device.
However, when I'm debugging, nothing happens. I think that the problem is that the UUID is wrong. I'm not sure how to get the devices to identify each other, in order to establish a connection.
I have read some other "questions" about those tags, but what I've tried didn't fix my problem:
Simple Bluetooth data receiver Android
Android: obtaining uuid of a bluetooth device
Etc...
Here's what I've written so far:
For tho android (Server) (This is the function that will make the connection)
public void connectSocket(){
blueAdapter.cancelDiscovery(); // Cancel discovery because it'll slow down the connection
final BluetoothServerSocket serverSocket;
BluetoothServerSocket sSocket= null;
try{
sSocket = blueAdapter.listenUsingRfcommWithServiceRecord("BluetoothJANE", MY_UUID);
}catch(IOException e){}
serverSocket = sSocket;
Thread acceptThread = new Thread(new Runnable() {
#Override
public void run() {
BluetoothSocket socket = null;
while(true){
try{
socket = serverSocket.accept();
}catch(IOException e){
break;
}
if(socket != null){
try{
iStream = socket.getInputStream();
oStream = socket.getOutputStream();
} catch(IOException e){}
}
}
}
});
acceptThread.start();
}
For java app on PC (This is the constructor of the class (it's on an independent thread) that will manage the bluetooth connection)
public ModuleBluetooth() {
StreamConnectionNotifier notifier = null;
StreamConnection connection = null;
try {
blueDevice = LocalDevice.getLocalDevice();
blueDevice.setDiscoverable(DiscoveryAgent.GIAC);
String url = "btspp://localhost:" + MY_UUID.toString()
+ ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (BluetoothStateException e) {
System.out
.println("ModuleBluetooth: Error getting the bluetooth device");
} catch (IOException e) {
}
System.out.println("waiting for connection...");
try {
connection = notifier.acceptAndOpen();
System.out.println("Conenction created");
} catch (IOException e) {
System.out.println("Can not create the connection");
}
}
Could somebody please help me? Any thoughts would be very much appreciated.
I have also tried to use some functions to acquire the UUID (in android) such as, [fetchUuidsWithSdp][2] (and the related functions) but eclipse doesn't recognize that functions (It seems that they don't exist in "my" API).
http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#fetchUuidsWithSdp%28%29
Try this example, http://luugiathuy.com/2011/02/android-java-bluetooth/ . I also had problem related to UUID, in this example, Converting UUID to 00001101-0000-1000-8000-00805F9B34FB worked out of the box. See this link: http://www.avetana-gmbh.de/avetana-gmbh/produkte/doc/javax/bluetooth/UUID.html
I am trying to connect to an openfire server using smack API, I am unable to do so.
Here is the code:
public class Tests{
public static void main( String[] args ) {
System.out.println("Starting IM client");
// gtalk requires this or your messages bounce back as errors
ConnectionConfiguration connConfig = new ConnectionConfiguration("localhost", 5222);
XMPPConnection connection = new XMPPConnection(connConfig);
try {
connection.connect();
System.out.println("Connected to " + connection.getHost());
} catch (XMPPException ex) {
//ex.printStackTrace();
System.out.println("Failed to connect to " + connection.getHost());
System.exit(1);
}
try {
connection.login("test#example.com", "setup1");
System.out.println("Logged in as " + connection.getUser());
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
} catch (XMPPException ex) {
//ex.printStackTrace();
System.out.println("Failed to log in as " + connection.getUser());
System.exit(1);
}
connection.disconnect();
}
}
The following is the output:
Starting IM client
Connected to localhost
Failed to log in as null
It seems to connect to the server but can't log in.
connection.login("test#example.com", "setup1");
You definitely shouldn't be logging in to example.com domain if your server is started on localhost.
Try just:
connection.login("test", "setup1");
But remember that to be able to login, you need to have a valid username and password. That means you have to create user "test" with password "setup1" on your server.
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]