better way to handle Connection refused when server is down - java

in Java, using Socket to connect into server with the following code will probably generate an error of java.net.ConnectException: Connection refused: when the server is down or not yet started.
try {
Socket clientSocket = new Socket(SERVER_IP, PORT);
} catch (IOException e) {
e.printStackTrace();
}
what is the best way to handle this exception? how do you continue trying to connect until server become available without having this issue?
UPDATE:
my method is to use UDP, send message into given port and then wait for a response in a given time, loop until I get a response before starting the socket.
I'm looking for a better approach.

What about something along these lines:
String SERVER_IP = "ip";
int PORT = 0;
int maxTries = 10;
int timeBeforeRetry = 5000; //ms
int count = 0;
Socket clientSocket = null;
while(clientSocket == null && count < maxTries) {
try {
clientSocket = new Socket(SERVER_IP, PORT);
} catch(IOException e) {
// Log if you want
try {
Thread.sleep(timeBeforeRetry);
} catch(InterruptedException e) { /* can be ignored or logged I guess */ }
}
count++;
}
if(clientSocket == null) {
// throw some kind of exception
}

Related

Android Socket Connections

Trying to run a loop to check if a IP is open.
for (int z = 0; z < 100; z++) {
String ip = "10.0.0." + z;
try {
log(ip);
Socket socket = new Socket(ip, MainActivity._util.getPort());
// Handle Stuff when Exception NOT throw
} catch (Exception e) {
}
}
log is a function I made (no errors there)
.getPort() is just a "global" port number I've defined
EDIT : That returns 2683 (just a random number)
it is supposed to just catch the exception then move on with the for loop but that doesn't happen.
Currently this just prints:
10.0.0.0
10.0.0.1
and then freezes.
If anyone has any advice that would be great!
EDIT
using socket.connect(new InetSocketAddress(ip, port), timeout) method still didn't handle correctly
This is in an AsyncTask extended class, in the doInBackground() method
There is no socket server to listen those IP and ports. So your socket client will be freeze. As mentioned here you should use another constructor for the socket and set timeout to prevent freezing.
for (int z = 0; z < 100; z++) {
String ip = "10.0.0." + z;
try {
log(ip);
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip, MainActivity._util.getPort()), 1000);
// Handle Stuff when Exception NOT throw
} catch (Exception e) {
}
}

#Java/Android Socket failed to read message

I have trouble with the Java Sockets.
I need to connect a server and a client through the local network and as there can be more then two devices connected to the router the Client must find out the Address of the server.
The only way I know to solve this problem is to get the three first numbers of the clients IP(v4)-address and loop every of the 254 other possible IPs.
(I know that this way is very slow and may cause many problems. If you know an alternative, I will be glad).
Actually the client is an android smartphone so I can get the DHCP-Info.
The problem is, that the read command to check if a device is a server will last forever.
If you need some code, here it is!
code:
onCreate:
final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
final String address = intToIp(dhcp.ipAddress);
String addresspart=address.substring(0, address.lastIndexOf('.')+1);
ArrayList<HashMap<String, String>> l = null;
Log.d("Keyboard","initiating search");
try {
l = new checkConnections().execute(addresspart).get();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
checkConnections:
ArrayList<HashMap<String,String>> l=new ArrayList<HashMap<String,String>>();
for(int i=1;i<=255;i++){
try {
worksocket=new Socket(addresspart[0]+i,61927);
workout=new BufferedOutputStream(worksocket.getOutputStream());
workin=new BufferedInputStream(worksocket.getInputStream());
byte[] buffer=new byte[6];
workin.read(buffer);//at this point the app freezes until you stop the serverside program
String answer=new String(buffer,"UTF-8");
Log.i("Keyboard","Welcome Message: "+answer);
if(answer.equalsIgnoreCase("sdk on")){
HashMap<String,String> hm=new HashMap<String,String>();
hm.put("address",addresspart[0]+i);
l.add(hm);
workout.write(intToBytes(8));
workout.write("closing".getBytes("UTF-8"));
worksocket.close();
continue;
}
else{
Log.d("Keyboard","No SDK-Programm detected");
worksocket.close();
continue;
}
} catch (UnknownHostException e) {
Log.d("Keyboard",addresspart[0]+i+" doesn't exists");
continue;
} catch ( InterruptedIOException e){
Log.w("System.warn",e.getCause()+e.getLocalizedMessage());
Log.d("Keyboard","timeout");
continue;
} catch (IOException e) {
Log.d("Keyboard",addresspart[0]+i+" doesn't exists");
e.printStackTrace();
continue;
}
}
return l;
the server's code:
ServerSocket serverSocket = new ServerSocket(61927);
System.out.println("Socket initiated");
Socket client = serverSocket.accept();
BufferedInputStream in=new BufferedInputStream(client.getInputStream());
BufferedOutputStream out=new BufferedOutputStream(client.getOutputStream());
System.out.println("client found");
byte[] buffer=new byte[11];
out.write("sdk on".getBytes("UTF-8"));
in.read(buffer);
String s=new String(buffer,"UTF-8");
if(!s.equals("got info")){
System.out.println("No SDK Client");
client.close();
serverSocket.close();
new Main();
}
Uh, I think I should ping the Broadcast-IP and listen for answers instead...
Android's Linux runtime allows it to read from which IP an answer is coming.

How to create multiple peer-to-peer chats within client-server messaging program

I am trying to create a messenger program and have successfully set up client-server connections using sockets. However I am finding it difficult to code the process of having several clients communicating simultaneously. Shown in the code below is the methods for the chats that are held within a ClientThread class that regulates the interaction between client and server using threads stored in a shared ArrayList. How would you implement the code for multiple peer-to-peer chats here?
startChat method:
public void startChat()
{
// start the convo!
// first of all the user chooses who to speak to
// starts a loop until user enters a valid username or 'Group'
String line = "";
boolean validCommand = false;
while(validCommand == false)
{
try {
line = in.readLine();
} catch (IOException e) {
System.out.println("Problem reading reply about user chat");
}
if(line.equalsIgnoreCase("Group"))
{
validCommand = true;
chatAll(); // an integer of negative one starts a chat with everyone
}
else
{
synchronized(this){
// find user
for(int i = 0; i < threads.size(); i++)
{
if(threads.get(i) != null && threads.get(i).username != null)
{
if(threads.get(i).username.equals(line)) // means that we have found the index of the thread that the client wants to speak to
{
/*// START : BETWEEN THESE CAPITALISED COMMENTS IS MY ATTEMPT TO INITIATE TWO WAY CHAT
int thisIndex = -1;
for(int j = 0; j < threads.size(); j++) // gets the index of this thread object in the array
{
if(threads.get(j) == this)
{
thisIndex = j;
// out.println(j);
}
}
if(thisIndex != -1)
{
threads.get(i).out.println(username + " is trying to connect");
threads.get(i).processChat(thisIndex); // this is the line causing the problem!
}
// END : BETWEEN THESE CAPITALISED COMMENTS IS MY ATTEMPT TO INITIATE TWO WAY CHAT */
threads.get(i).out.println(username + " is trying to connect");
out.println("Chat with " + threads.get(i).username);
processChat(i);
validCommand = true;
}
// if the command is not group and not a username, it is not valid and we ask the user to re-enter
else if(i == threads.size() - 1)
{
out.println("This command is not valid, please re-enter");
}
}
}
} // end of synchronised bit
} // end of else statement
} // end of while loop
}
allChat method:
void chatAll()
//for the purpose of group chat
{
out.println("Group chat initiated");
boolean d = true;
while(d == true)
{
String message = "";
try {
message = in.readLine();
} catch (IOException e) {
System.out.println("Can't read line from client");
}
if(message.contains("goodbye") == true)
{
d = false;
}
else
{
synchronized(this)
{
for(int j = 0; j < threads.size(); j++)
{
if(threads.get(j) != null)
{
threads.get(j).out.println(username + ": " + message);
}
}
}
}
}
}
processChat method:
void processChat(int i)
//for the purpose of talking to pre-defined user
{
boolean d = true;
while(d == true)
{
String message = "";
try {
message = in.readLine();
} catch (IOException e) {
System.out.println("Can't read message from client");
}
if(message.contains("goodbye") == true)
{
d = false;
}
else {
if(threads.get(i) != null)
{
threads.get(i).out.println(username + ": " + message);
}
}
}
}
Just for good measure and a reference here is the overall client class (confusingly labelled ThreadedClient as opposed to ClientThread haha)
ThreadedClient class:
import java.net.*;
import java.io.*;
public class ThreadedClient implements Runnable {
// client socket
private static Socket clientSocket = null;
//I/O streams to and from the server
private static BufferedReader in = null;
private static PrintStream out = null;
// Input stream to read user input
private static BufferedReader inputReader = null;
private boolean open = true;
public ThreadedClient(String host, int port)
{
startConnection(host, port);
}
public void startConnection(String host, int port)
{
//open up the socket
try {
clientSocket = new Socket(host, port);
} catch (UnknownHostException e) {
System.out.println("The host name '" + host + "' isn't known");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Cannot create socket");
}
// connect I/O streams
try {
in = new BufferedReader(new InputStreamReader(new DataInputStream(clientSocket.getInputStream())));
out = new PrintStream(clientSocket.getOutputStream());
inputReader = new BufferedReader(new InputStreamReader(System.in));
} catch (IOException e) {
System.out.println("Problem connecting streams");
}
// process the chat itself
// the thread deals with input coming in
Thread thread = new Thread(this);
thread.start();
// the loop deals with output
while(open == true)
{
String message;
try {
message = inputReader.readLine();
out.println(message);
if(message.contains("goodbye") == true)
{
open = false;
}
} catch (IOException e) {
System.out.println("Problem sending messages");
}
}
// chat is done, so we can close resources
try {
in.close();
inputReader.close();
out.close();
clientSocket.close();
} catch (IOException e) {
System.out.println("Problem closing resources");
}
}
// run method for sending input out. I imagine this will not be necessary in the GUI implemented version, as we can use
// an action listener for the send function, e.g. one that reads a text field into a output stream everytime the user clicks enter
public void run() {
while(open == true)
{
try {
String response = in.readLine();
if(response.contains("goodbye") == true)
{
open = false;
}
System.out.println(response);
} catch (IOException e) {
System.out.println("Problem recieving messages");
}
}
}
public static void main(String[] args)
{
ThreadedClient socket = new ThreadedClient("localhost", 50000);
}
}
I know that this code may not be as advanced as some others I have seen on this forum as well as DreamInCode and others but I was trying to build it from scratch and have been stuck here for what feels like a millennia. Trawling through the internet has not helped :(
Any suggestions and criticisms would be an absolute God send!
Thanks in advance guys.
OK.
You can do like this: Im focus on Console Application
- Define a class call Message:
class Message
{
public String username; // the sender that send this message to u.So you can reply back to this user
public boolean groupMessage; // this message is group message or not
public String message;
}
Define a global variable: ArrayList messages; to hold all incomming messages.
So when you start chat with a client --> create new Thread to read message from him.When you receive a message . You have to put that message to the array list: messages ( you have to remember to sync it. because it will be invoked by many thread)
synchorized(messages){
messages.add(....); // new message here
}
Then , you create a new Thread to show message & can reply back to the sender. In this read you will pop a message from array list messages & show it.
while(isrunning)
{
synchorized(messages){
if(messages.size()<=0) messages.wait(); // when you receive a new message you have to notify
}
synchorized(messages){
Message msg = messages.get(0);
messages.remove(0);
showmessage_to_ouput(msg); // something like this.
String s = read from input // to reply to this message.
Reply(....)// here you can check if this message is group message--> reply to all,..etc
}
}
P/S: That's a idea :) good luck
I can give you a solution , but you have to implement it
We have:
- Server A, Client B & C. B & C already connected to Server via TCP connection
- The first, client B want to chat with C. So B have to send a message by UDP to server
- 2nd, Server will receive a UDP messages from B ==> Server know which ip & port of B that B connected to Server by UDP. Then server send to C a message (TCP) that contains info about UDP ip:port of B .
- 3rd: Client C will receive that message from server via TCP . So C know ip:port that B is listenning .--> If C accept chat with B . C have to send a UDP message to Server to tell server that C accept to talk with B.
- 4th: Server will receive that message via UDP . So Server also know ip:port of C in UDP.
- 5th : The server will transfer UDP ip:port of C to B via TCP (or UDP if you want).
- 6th: Client B will receive it & know udp ip:port of C. So they can start to chat via UDP protocol now.
IT is call UDP/TCP Hole punching. You can research more about it to implement.
P/S: But this method doesnt work with Symetric NAT

server doesn't receive data from multiple clients (java sockets)

I wrote a simple program where a server should print data sent by multiple clients. But the server receives only partial data. Following are the relevant pieces of the code.
Server:
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on port: 8888");
System.exit(-1);
}
while (listening) {
Socket clientSocket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
System.out.println(reader.readLine());
reader.close();
clientSocket.close();
}
serverSocket.close();
Client:
try {
socket = new Socket("nimbus", 8888);
writer = new PrintWriter(socket.getOutputStream(), true);
localHost = InetAddress.getLocalHost();
}
catch (UnknownHostException e) {}
catch (IOException e) {}
StringBuilder msg1 = new StringBuilder("A: ");
for(int i=1; i<=3; i++)
msg1.append(i).append(' ');
writer.println(localHost.getHostName() + " - " + msg1);
StringBuilder msg2 = new StringBuilder("B: ");
for(int i=4; i<=6; i++)
msg2.append(i).append(' ');
writer.println(localHost.getHostName() + " - " + msg2);
StringBuilder msg3 = new StringBuilder("C: ");
for(int i=7; i<=9; i++)
msg3.append(i).append(' ');
writer.println(localHost.getHostName() + " - " + msg3);
writer.close();
socket.close();
I get the following output (when run on 3 clients)
nimbus2 - A: 1 2 3
nimbus3 - A: 1 2 3
nimbus4 - A: 1 2 3
I don't get the second and third messages. Server keeps waiting. Where am I going wrong?
Edit: In the server code, I tried removing reader.close() and clientSocket.close(). That didn't work either. Another question -- if 3 clients send 3 messages, does it require 9 connections? (this is the reason, I closed the connection in the server code)
You probably want to be delegating the handing of the socket to another thread. I've written up an example that works by passing each incoming socket to an Executor so it can read all the inputs. I use a Executors.newCachedThreadPool() which should grow to be as big as needed. You could also use Executors.newFixedThreadPool(1) if you want it to only be able to handle 1 client at a time.
The only other change I made was I removed the BufferedReader and replaced it with a Scanner. I was having issues with the BufferedReader not returning data. I'm not sure why.
Executor exe = Executors.newCachedThreadPool();
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on port: 8888");
System.exit(-1);
}
while (listening) {
final Socket clientSocket = serverSocket.accept();
exe.execute(new Runnable() {
#Override
public void run() {
try {
Scanner reader = new Scanner(clientSocket.getInputStream());
while(reader.hasNextLine()){
String line = reader.nextLine();
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
serverSocket.close();
It looks like you close the connection to the client before they can finish writing/before the server reads all of the messages they sent. I think you need to continue to readline, and potentially not terminate the client's connection after they send you one message.
John is right.
you close the client connection by calling clientsocket.close() after reading the message that is why you cannot get the other messages. you should call clientsocket.close() when you have received all the messages

cannot get server socket to close

I'm making a simple chat server and just made it so each connection runs on a new thread.
The old version started a single thread for the server, it did a while loop, which would stop when a stop message was sent then close the socket.
The new version loops forever and create a new thread for each new connection. Now I cannot close the socket connection.
If you press a key and the main thread stops, the socket stays open. Thus when I run the program again I need to change the socket number.
code of server
while(true)
{
///////////////////////////////////////////////////
// get a new connection
///////////////////////////////////////////////////
System.out.println("Aceepting connections on port 1030 \r");
try{
// Get New Connection
// wait for ever on accepting new connections
server.setSoTimeout(0);
connection=server.accept();
cConnection thread = new cConnection("thread3", connection);
} catch(IOException ec)
{
System.out.println(ec.getMessage());
}
}
code that starts server
Now each message comes in on a new thread, so I cannot tell it to stop and close the socket.
You need to provide a flag that must be globally accesible, so when some client wants to stop the server then change the variable ans stops the bucle. By example:
class YourServer {
private static boolean execute = true;
public static synchronized void stop() {
execute = false;
}
public void yourMethod() {
while(execute) {
// implement your server here
}
}
}
When a client send the command STOP you must be do
YourServer.stop();
If you want a stop command to stop the server you can call System.exit() to force the program to store or just closing server is likely to be all you need.
Looking into your problem, I understood one thing, that since you are putting
while (true), so your control always gets stuck at connection=server.accept(); listening for a new connection. So in order to stop the sockets you need to first find a way to stop looping in that while loop. Either you can set a Variable, like (int clientsConnected) to check the number of Clients, when that comes to zero stop that while loop. So you can stop your sockets.
Below is my sample code for clients which is doing the same thing for closing the Sockets.
Hopefully this solves your problem.
class GetNamesFromServer implements Runnable
{
private Socket sForName, sForId;
private BufferedReader in, inForName, inForId;
private PrintWriter outForName, outForId;
private static String clientNames;
public GetNamesFromServer(Socket s1, Socket s2)
{
sForName = s1;
sForId = s2;
}
public void run()
{
try
{
outForName = new PrintWriter(sForName.getOutputStream(), true);
outForName.println(Client.clientName);
System.out.println("Send Name : " + Client.clientName);
outForName.flush();
}
catch(IOException e)
{
System.err.println("Error sending Name to the Server.");
}
try
{
inForId = new BufferedReader(new InputStreamReader(sForId.getInputStream()));
Client.clientId = (inForId.readLine()).trim();
System.out.println("Client ID is : " + Client.clientId);
}
catch(IOException e)
{
System.err.println("Error Receiving ID from Server.");
}
try
{
inForName = new BufferedReader(new InputStreamReader(sForName.getInputStream()));
while (true)
{
clientNames = inForName.readLine();
if (clientNames != null && clientNames != "")
{
clientNames = clientNames.substring(1, clientNames.length() - 1);
System.out.println("Names Received : " + clientNames);
String[] names = clientNames.split(", ");
Client.nameClients.clear();
for (String element: names)
Client.nameClients.add(element);
Client.nPane.setText("");
int size = Client.nameClients.size();
System.out.println("Size of list : " + size);
for (int i = 0; i < size; i++)
{
String name = Client.nameClients.get(i);
String colour = Character.toString(name.charAt(0));
name = name.substring(1, name.length()) + "\n";
appendToNamePane(name, ReceiveMessages.getColour(Integer.parseInt(colour)), "Lucida Console");
}
System.out.println("Clients Online : " + Client.nameClients);
}
int index = Client.nameClients.indexOf(Client.clientId + Client.clientName);
**if (index == -1)
{
sForName.close();
break;
}**
}
}
catch(IOException e)
{
System.err.println("Error Receiving Names of Clients from Server");
}
}
NEW EDITION :
You can add a cap to maximum number of clients that can connect, once that reaches your while loop will not go to connection = server.accept(); and hence when they are done chatting (after some time) i.e. totalClients = 0, you can stop your sockets as well, to stop the program.
if (totalClients == 0)
{
socket.close();
serverSocket.close();
}
Regards

Categories

Resources