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.
Related
I am trying to connecting a server with FTPSClient (true implicit), port 990, and it seems the connection is ok, but it says that the file PDF inside cannot be found.
String protocol = "TLS"; // TLS / SSL
boolean isImpicit = true;
int timeoutInMillis = 3000;
FTPSClient client = new FTPSClient(protocol, isImpicit);
client.setDataTimeout(timeoutInMillis);
client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
try
{
int reply;
client.connect(server, port);
client.login(user, pass);
client.setFileType(FTP.BINARY_FILE_TYPE);
client.execPBSZ(0);
client.execPROT("P");
System.out.println("Connected to " + server + ".");
reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
client.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
client.listFiles();
boolean retrieved = client.retrieveFile(Constantes.DIRECCION_FTP_PDF_FACTURAS + nombre_factura, new FileOutputStream(Constantes.DIRECCION_FTP_LOCAL_DESCARGAS + nombre_factura));
}
catch (Exception e)
{
if (client.isConnected())
{
try
{
client.disconnect();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
System.err.println("Could not connect to server.");
e.printStackTrace();
return;
}
finally
{
System.out.println("# client disconnected");
client.disconnect();
}
}
The error I got is java.io.FileNotFoundException
I tried writing the full path since C:\ , and without it, but nothing works.
Anybody can help me?
Thanks.
EDIT: IT WORKS NOW!
The path "Program Files" contains a space and maybe FileInputStream does not manage to resolve it properly.
May give it a try to put your folder to "C:/Temp/" and test it again.
Where does this FileNotFoundException happen exactly?
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 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);
}
}
i want to connect morethan one client at a time to the server and also communicate server to all the clients.
how server recognize each client. and how to send data to a particular client?
consider , there are 3 clients A,B,C. all the clients are connected to the server. the server wants to send message to B. how its done ?
If i understand you right - all you need is not bind socket for one connection.
Your client code will looks like that:
Client class:
public class TCPClient {
public TCPClient(String host, int port) {
try {
clientSocket = new Socket(host, port);
} catch (IOException e) {
System.out.println(" Could not connect on port: " + port + " to " + host);
}
}
Server(host) class:
public class TCPListener {
public TCPListener(int portNumber) {
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println("Could not listen on port: " + portNumber);
}
System.out.println("TCPListener created!");
System.out.println("Connection accepted");
try {
while (true) {
Socket clientConnection = serverSocket.accept();
//every time client's class constructor called - line above will be executed and new connection saved into Socket class.
}
} catch (Exception e) {
e.printStackTrace();
}
}
That is simplest example. More can be found here:
http://www.oracle.com/technetwork/java/socket-140484.html