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
Related
I have written a client to run on an android device (android 6) and when the server is up and running it connects, however when the server is down the socket() call should throw an exception however it doesn't.
I originally tried it using the NDK and ran into a very similar issue (Android NDK socket connect() returning 0 when it should fail whilst on 3g).
I am assuming this is a bug with android at this point but any insight into a solution or work around would be much appreciated.
The code in question:
public class Client implements Runnable{
private Socket socket;
private InetAddress IP;
private int port;
public Client(int port){
try {
this.IP = InetAddress.getByName(server ip);
}
catch(UnknownHostException e){
Log.d("App1", "Unknown Host, connection failed");
System.exit(1);
}
this.port = port;
Log.d("App1", "initialised");
}
#Override
public void run(){
try {
this.socket = new Socket(this.IP, this.port);
Log.d("FiX1", "Connected");
listen();
}
catch(IOException e){
Log.d("FiX1,","connection failed");
System.exit(1);
}
finally
{
try{
socket.close(); // dispose
}
catch(IOException e){
System.exit(1);
}
}
}
public void listen() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String cominginText = "";
try {
cominginText = in.readLine();
Log.d("FiX1",cominginText);
} catch (IOException e) {
//error ("System: " + "Connection to server lost!");
System.exit(1);
break;
}
}
} catch (IOException e) {
System.exit(1);
}
}
}
The best solution I could find was to manually send an acknowledgement from the server that a connection had been made, the client would retry the connection if it did not receive this message within a certain time after it claimed to have connected.
There is a difference between a TCP connection "close" vs "disconnect".
If you close the socket connection from server using socket.close() then you will get exception in client side, if you try to read from that connection or vice versa.
However, if one side just disappears(shut down the program) then the other side has no way of knowing that. So the other side will wait for response for read call.
The TCP protocol was designed to be reliable in hostile communication environments and it will not normally decide a connection is closed just because it has not heard from the other side for a while.
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 have a TCP Server written in java. I am trying to connect to it via a TCP client socket written in dartlang but the client written in dartlang times out almost immediately after the initial connection (my five second timeout set in the java code). I was able to send a message to the dart client in a test immediately after it connected but it soon timed out. However the data in the dartlang '{"packet_id":1}' never gets received by the server.
I tried writing a test server in dartlang and it was able to connect and send/receive messages without any issues.
Dart Client:
import 'dart:io';
import 'dart:async';
main(List<String> arguments) {
Future<Socket> future = Socket.connect('localhost', 12345);
future.then((client) {
print('connected to server!');
client.handleError((data){
print(data);
});
client.listen(
(data) {
print(new String.fromCharCodes(data));
},
onDone:(){
print("Done");},
onError: (error) {
print(error);
}
);
String requestHalls = '{"packet_id":1}';
client.write(requestHalls);
}).catchError(() {print('Error connecting');});
print('Hello world: ${dart_test.calculate()}!');
}
My Java client connects to the Java Server socket just fine.
EDIT: adding java code
creating the serversocket.
#Override
public void run() {
// Create Server Socket for clients to connect to
try {
// load data from config manager
ConfigManager config = HDAServer.getConfigManager();
int port = config.getServerPort();
String ip = config.getServerURL();
Inet4Address inet4 = (Inet4Address) Inet4Address.getByName(ip); // this allows for binding to domain name or ipv4 address
HDAServer.getLogger().info(String.format("Opening Server Socket at address(%s)= %s:%s", ip, inet4.getHostAddress(), port));
// attempt to bind
serverSocket = new ServerSocket(config.getServerPort(), 50, inet4);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// wait for incoming client connections
waitForConnections();
}
/**
* Method that waits for incoming connections, adds the connection to a new pool, and creates a
* new thread for the connection to run on.
*/
private void waitForConnections() {
// loop through waiting for incoming connections until server shuts down
while (!shutdown) {
Socket socket = null;
try {
// blocks thread waiting for a connection
socket = serverSocket.accept();
} catch (IOException e) {
if (e.getMessage().equals("socket closed")) {
HDAServer.getLogger().info("Shutting Down Server Socket");
continue;// skip to while check
} else {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// create our connection class, start it in a new thread, and add it to our connection list
HDAServerConnection newConn = new HDAServerConnection(socket);
new Thread(newConn).start();
connections.add(newConn);
HDAServer.getLogger().info(String.format("Client connected from: %1s", newConn.getRemoteIP()));
// reap dead connections
this.reapDeadConnections();
}
}
Servers "Client" HDAConnection class:
protected Socket socket;
protected DataInputStream inputStream;
protected DataOutputStream outputStream;
private boolean shutdown = false;
public HDAConnection(Socket socket) {
this.socket = socket;
// configure socket
try {
socket.setKeepAlive(true);
socket.setSoTimeout(5000);
socket.setTcpNoDelay(true);
} catch (SocketException ex) {
AbstractHDALogger.get().severe("Error configuring Socket Connection.", ex);
}
// create input/output stream for handling data
try {
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) {
AbstractHDALogger.get().severe("Error creating input/output streams.", ex);
}
}
code that is listening for a message over the stream.
String response = null;
try {
response = new BufferedReader(new InputStreamReader(inputStream)).readLine();
} catch(SocketTimeoutException ste) {
shutdown();
AbstractHDALogger.get().severe(String.format("Socket Timed out(%s), closing Connection", this.getRemoteIP()), ste);
// TODO: handle exception
} catch (IOException e) {
// TODO Make this better?
// IO Exception probably means client disconnected, so we should terminate.
if (e.getMessage().equals("Connection reset")) {
shutdown();
AbstractHDALogger.get().info(String.format("Client Connection Disconnected(%s). Closing connection.", this.getRemoteIP()));
} else {
shutdown();
AbstractHDALogger.get().severe(String.format("Connection Error(%s), closing Connection", this.getRemoteIP()), e);
}
return null;
}
The socket is timing out on the Java Server because the dartlang client is never writing a newline at the end of its message and the Java Server is using the readline method to read. This function will only return when it reads a new line character. After reading the initial message from the dartlang client the Java server waits five seconds for more data to be sent but will time out as nothing more is ever sent.
The dartlang client should use the writeln function or appent a newline character to the end of its messages for the Java server BufferedReader to return.
I am facing this current problem now.
I am able to send command to the device and receive response from the device from android emulator to the socket.
But, when I install the same application on tablet, there is a problem. The first time I send command to check status that device is connected or not, it send me the response that device is connected but when I send command second time it throws the following exception:
java.net.ConnectException: /192.168.1.106:8002 - Connection refused.
This is the code that does the request:
public static String sendRequestandResponse(final String host,final int port,
final String command,
final int timeoutInMillis,final int responseLength) throws UnknownHostException,NetworkSettingException
{
if (host == null)
{
throw new NullPointerException("host is null"); //NOPMD
}
Socket clientSocket=null;
try {
/**
* Creating socket connection with IP address and port number to send Command
*/
try{
clientSocket = new Socket();
SocketAddress remoteAdr = new InetSocketAddress(host, port);
clientSocket.connect(remoteAdr, 1000);
clientSocket.setSoTimeout(timeoutInMillis);
}catch (Exception e) {
e.printStackTrace();
throw new NetworkSettingException(e.getMessage());
}
final PrintWriter outPutStream = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), CHARSET));
try
{
outPutStream.print(command);
outPutStream.flush();
BufferedReader responseString = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), CHARSET));
response = new StringBuilder();
try
{
int pos = 0;
while (true)
{
pos++;
System.out.println(pos);
int i=responseString.read();
byte[] resp={(byte)i};
System.out.println(new String(resp));
response.append(new String(resp));
if(pos>=responseLength){
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Log.d("ConnectionSocket", "Socket closed with break");
break;
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
finally
{
responseString.close();
}
}
finally
{
outPutStream.close();
}
}
catch(IOException ex){
}
catch(NullPointerException ex){ //NOPMD
}
finally
{
try {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
} catch (NullPointerException ex) { //NOPMD
} catch (IOException ex) {
}
}
return response.toString();
}
I think it doesnt close the socket first time, so second time it refuse the connection.
The same code works on emulator though.
You will get the Connection Refused only when the server is not accepting the connection.
Mostly, the Problem is the Firewall which blocks the any untrusted incoming connection.
My application shows this message mostly when the server has a firewall which block it.
So u can add the Exception list in Firewall for your application.
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