Java - Find Server in network - java

I want to find my Server in my network, when I don't know the ip.
So that's the code I have, but it takes really (!) long to test all IPs:
for (int j = 1; j < 255; j++) {
for (int i = 1; i < 255; i++) {
String iIPv4 = "192.168." + j + ".";
try {
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(iIPv4 + i, 2652 );
socket.connect(address, 5);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fromServer;
while ((fromServer = in.readLine()) != null) {
if (fromServer.equals("Connected to CC3000")) {
System.out.println("CC3000 found! : " + iIPv4 + i);
return iIPv4 + i;
}
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
}
so, whats a better way to find the server?
regards

I think that multithreading could help you here, since you don't want to be waiting for each connection to either establish or fail.
You can try say hundreds of sockets at once instead. Also checking that IP is reachable might save you some time.
Code below is really a naive and horrible example since there's no thread management at all, but you get the picture I hope. You should get the result much faster.
public static void findLanSocket(final int port, final int timeout) {
List<Thread> pool = new ArrayList<>();
for (int j = 1; j < 255; j++) {
for (int i = 1; i < 255; i++) {
final String iIPv4 = "192.168." + j + "." + i;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("TESTING: " + iIPv4);
try {
// First check if IP is reachable at all.
InetAddress ip = InetAddress.getByName(iIPv4);
if (!ip.isReachable(timeout)) {
return;
}
// Address is reachable -> try connecting to socket.
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(ip, port);
socket.connect(address, timeout);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fromServer;
while ((fromServer = in.readLine()) != null) {
if (fromServer.equals("Connected to CC3000")) {
System.out.println("CC3000 found! : " + iIPv4);
}
}
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
});
pool.add(thread);
thread.start();
}
}
// Wait for threads to die.
for (Thread thread : pool) {
try {
if (thread.isAlive()) {
thread.join();
}
} catch (InterruptedException ex) {
}
}
}

Related

What is the problem of this code...? Java socket programming

I am coding client-server multithread calculator using java, socket programming.
There's any syntax error, but msgs cannot be received from server.
I think
receiveString = inFromServer.readLine()
does not works. This code is in Client program, in the while(true) loop.
What is the problem?
Here is my full code.
SERVER
import java.io.*;
import java.net.*;
public class Server implements Runnable
{
static int max = 5; //maximum thread's number
static int i = 0, count = 0; //i for for-loop, count for count number of threads
public static void main(String args[]) throws IOException
{
ServerSocket serverSocket = new ServerSocket(6789); //open new socket
File file = new File("src/serverinfo.dat"); //make data file to save server info.
System.out.println("Maximum 5 users can be supported.\nWaiting...");
for(i=0; i <= max; i++) { new Connection(serverSocket); } //make sockets - loop for max(=5) times
try //server information file writing
{
String dataString = "Max thread = 5\nServer IP = 127.0.0.1\nServer socket = 6789\n";
#SuppressWarnings("resource")
FileWriter dataFile = new FileWriter(file);
dataFile.write(dataString);
}
catch(FileNotFoundException e) { e.printStackTrace(); }
catch(IOException e) { e.printStackTrace(); }
}
static class Connection extends Thread
{
private ServerSocket serverSocket;
public Connection(ServerSocket serverSock)
{
this.serverSocket = serverSock;
start();
}
public void run()
{
Socket acceptSocket = null;
BufferedReader inFromClient = null;
DataOutputStream msgToClient = null;
String receiveString = null;
String result = "", sys_msg = "";
try
{
while(true)
{
acceptSocket = serverSocket.accept(); // 접속수락 소켓
count++;
inFromClient = new BufferedReader(new InputStreamReader(acceptSocket.getInputStream()));
msgToClient = new DataOutputStream(acceptSocket.getOutputStream());
System.out.println(count + "th client connected: " + acceptSocket.getInetAddress().getHostName() + " " + count + "/" + max);
System.out.println("Waiting response...");
while(true)
{
if (count >= max+1) // if 6th client tries to access
{
System.out.println("Server is too busy. " + max + " clients are already connected. Client access denied.");
sys_msg = "DENIED";
msgToClient.writeBytes(sys_msg);
acceptSocket.close();
count--;
break;
}
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
try{ receiveString = inFromClient.readLine(); }
catch(Exception e) // if receiveString = null
{
System.out.println("Connection Close");
count--;
break;
}
System.out.println("Input from client : " + receiveString);
try
{
if(receiveString.indexOf("+") != -1) { result = cal("+", receiveString); }
else if(receiveString.indexOf("-") != -1) { result = cal("-", receiveString); }
else if(receiveString.indexOf("/") != -1) { result = cal("/", receiveString); }
else if(receiveString.indexOf("*") != -1) { result = cal("*", receiveString); }
else if(receiveString.indexOf("+") == -1 || receiveString.indexOf("-") == -1 || receiveString.indexOf("*") == -1 || receiveString.indexOf("/") == -1) { result = "No INPUT or Invalid operation"; }
}
catch(Exception e){ result = "Wrong INPUT"; }
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
}
}
}
catch(IOException e) { e.printStackTrace(); }
}
}
private static String cal(String op, String recv) //function for calculating
{
double digit1, digit2; //first number, second number
String result = null;
digit1 = Integer.parseInt(recv.substring(0, recv.indexOf(op)).trim());
digit2 = Integer.parseInt(recv.substring(recv.indexOf(op)+1, recv.length()).trim());
if(op.equals("+")) { result = digit1 + " + " + digit2 + " = " + (digit1 + digit2); }
else if(op.equals("-")) { result = digit1 + " - " + digit2 + " = " + (digit1 - digit2); }
else if(op.equals("*")) { result = digit1 + " * " + digit2 + " = " + (digit1 * digit2); }
else if(op.equals("/"))
{
if(digit2 == 0){ result = "ERROR OCCURRED: Cannot be divided by ZERO"; }
else{ result = digit1 + " / " + digit2 + " = " + (digit1 / digit2); }
}
return result;
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
-----------------------------------------------------------------
CLIENT
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws IOException
{
Socket clientSocket = null;
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromServer = null;
DataOutputStream msgToServer = null;
String sendString = "", receiveString = "";
try
{
clientSocket = new Socket("127.0.0.1", 6789); //make new clientSocket
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
msgToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Input exit to terminate");
System.out.println("Connection Success... Waiting for permission");
while(true)
{
receiveString = inFromServer.readLine();
if(receiveString.equals("DENIED"))
{
System.out.println("Server is full. Try again later.");
break;
}
else { System.out.println("Connection permitted."); }
System.out.print("Input an expression to calculate(ex. 3+1): ");
sendString = userInput.readLine();
if(sendString.equalsIgnoreCase("exit")) //when user input is "exit" -> terminate
{
clientSocket.close();
System.out.println("Program terminated.");
break;
}
try { msgToServer.writeBytes(sendString); }
catch(Exception e) {}
try { receiveString = userInput.readLine(); }
catch(Exception e) {}
System.out.println("Result: " + receiveString); //print result
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You've set up your server socket stack wrong.
Your code will make 5 threads, each calling accept on a serversocket.
The idea is to have a single ServerSocket (and not 5, as in your example). Then, this single serversocket (running in a single thread that handles incoming sockets flowing out of this serversocket) will call .accept which will block (freeze the thread) until a connection is made, and will then return a Socket object. You'd then spin off a thread to handle the socket object, and go right back to the accept call. If you want to 'pool' (which is not a bad idea), then disassociate the notion of 'handles connections' from 'extends Thread'. For example, implement Runnable instead. Then pre-create the entire pool (for example, 10 threads), have some code that lets you 'grab a thread' from the pool and 'return a thread' to the pool, and now the serversocket thread will, upon accept returning a socket object, grab a thread from the pool (which will block, thus also blocking any incoming clients, if every thread in the pool is already taken out and busy handling a connection), until a thread returns to the pool. Alternatively, the serversocket code checks if the pool is completely drained and if so, will put on a final thread the job of responding to that client 'no can do, we are full right now'.
I'm not sure if you actually want that; just.. make 1 thread per incoming socket is a lot simpler. I wouldn't dive into pool concepts until you really need them, and if you do, I'd look for libraries that help manage them. I think further advice on that goes beyond the scope of this question, so I'll leave the first paragraph as an outlay of how ServerSocket code ought to work, for context.

TCP sockets returning strange thing in Java

I have socket application that i use for communication with a device.
When i open socket i can read status outputs from the machine.
Machine sends some data which is separated by comma ',' and i need to parse only numbers.
The problem is when i parse the data i recieve numbers but i also recieve "empty" strings.
Here is my code:
void startListenForTCP(String ipaddress) {
Thread TCPListenerThread;
TCPListenerThread = new Thread(new Runnable() {
#Override
public void run() {
Boolean run = true;
String serverMessage = null;
InetAddress serverAddr = null;
BufferedWriter out = null;
int redni = 0;
try {
Socket clientSocket = new Socket(ipaddress, 7420);
try {
mc.pushNumbers("Connection initiated... waiting for outputs!"
+ "\n");
char[] buffer = new char[2];
int charsRead = 0;
out =
new BufferedWriter(new OutputStreamWriter(
clientSocket.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((charsRead = in.read(buffer)) != -1) {
String message = new String(buffer).substring(0, charsRead);
if (message.equals("I,")) {
mc.pushNumbers("\n");
} else {
String m = message;
m = m.replaceAll("[^\\d.]", "");
String stabilo = m;
int length = stabilo.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = stabilo.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("Result:" + m);
}
}
} catch (UnknownHostException e) {
mc.pushNumbers("Unknown host..." + "\n");
} catch (IOException e) {
mc.pushNumbers("IO Error..." + "\n");
} finally {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
mc.pushNumbers("Connection refused by machine..." + "\n");
}
}
});
TCPListenerThread.start();
}
And the System.out.println(); returns this:
Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:26Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:Result:13
Result:Result:Result:Result:Result:Result:Result:Result:Result:
I just don't know why I can't parse only numbers, there is probably something that machine sends and it isn't parsed by m = m.replaceAll("[^\\d.]", "");
You're building your String incorrectly. It should be:
String message = new String(buffer, 0, bytesRead);
where 'bytesRead' is the count returned by the read() method. It's a byte count, not a char count.

multi client error with java multithreading

Below is the code for a client and server which handles multi user chat. But when one client writes "quit" my others current connected client also terminates and I can't then connect another client. Can anybody help with this?
Here is my client code:
class TCPClientsc {
public static void main(String argv[]) throws Exception {
String modifiedSentence;
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println(inetAddress);
Socket clientSocket = new Socket(inetAddress, 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
CThread write = new CThread(inFromServer, outToServer, 0, clientSocket);
CThread read = new CThread(inFromServer, outToServer, 1, clientSocket);
}
}
class CThread extends Thread {
BufferedReader inFromServer;
DataOutputStream outToServer;
Socket clientSocket = null;
int RW_Flag;
public CThread(BufferedReader in, DataOutputStream out, int rwFlag, Socket clSocket) {
inFromServer = in;
outToServer = out;
RW_Flag = rwFlag;
clientSocket = clSocket;
start();
}
public void run() {
String sentence;
try {
while (true) {
if (RW_Flag == 0) {// write
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
sentence = inFromUser.readLine();
// System.out.println("Writing ");
outToServer.writeBytes(sentence + '\n');
if (sentence.equals("quit"))
break;
} else if (RW_Flag == 1) {
sentence = inFromServer.readLine();
if (sentence.endsWith("quit"))
break;
System.out.println("(received)" + sentence);
}
}
} catch (Exception e) {
} finally {
try {
inFromServer.close();
outToServer.close();
clientSocket.close();
} catch (IOException ex) {
Logger.getLogger(CThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Server code:
class TCPServersc {
static int i = 0;
static SThread tt[] = new SThread[100];
static SThread anot[] = new SThread[100];
public static void main(String argv[]) throws Exception {
String client;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
i++;
System.out.println("connection :" + i);
BufferedReader inFromClient = new BufferedReader(newInputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
BufferedReader inFromMe = new BufferedReader(new InputStreamReader(System.in));
tt[i] = new SThread(inFromClient, outToClient, tt, 0, connectionSocket, i);
anot[i] = new SThread(inFromMe, outToClient, tt, 1, connectionSocket, i);
}
}
}
// ===========================================================
class SThread extends Thread {
BufferedReader inFromClient;
DataOutputStream outToClient;
String clientSentence;
SThread t[];
String client;
int status;
Socket connectionSocket;
int number;
public SThread(BufferedReader in, DataOutputStream out, SThread[] t, int status, Socket cn, int number) {
inFromClient = in;
outToClient = out;
this.t = t;
this.status = status;
connectionSocket = cn;
this.number = number;
start();
}
public void run() {
try {
if (status == 0) {
clientSentence = inFromClient.readLine();
StringTokenizer sentence = new StringTokenizer(clientSentence, " ");
// ///////////////////////////////////////////////////////////
if (sentence.nextToken().equals("login")) {
String user = sentence.nextToken();
String pass = sentence.nextToken();
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
int flag = 0;
while ((client = br.readLine()) != null) {
if ((user.equals(client.substring(0, 5))) && (pass.equals(client.substring(6, 10)))) {
flag = 1;
System.out.println(user + " has logged on");
for (int j = 1; j <= 20; j++) {
if (t[j] != null)
t[j].outToClient.writeBytes(user + " has logged on" + '\n');// '\n' is necessary
}
break;
}
}
if (flag == 1) {
while (true) {
clientSentence = inFromClient.readLine();
System.out.println(user + " : " + clientSentence);
for (int j = 1; j <= 20; j++) {
if (t[j] != null)
// '\n' is necessary
t[j].outToClient.writeBytes(user + " : " + clientSentence + '\n');
}
// if(clientSentence.equals("quit"))break;
}
}
}
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (status == 1) {
while (true) {
clientSentence = inFromClient.readLine();
if (clientSentence.equals("quit"))
break;
System.out.println("Server: " + clientSentence);
for (int j = 1; j <= 20; j++) {
if (t[j] != null)
t[j].outToClient.writeBytes("Server :" + clientSentence + '\n');// '\n' is necessary
}
}
}
} catch (Exception e) {
} finally {
try {
// System.out.println(this.t);
inFromClient.close();
outToClient.close();
connectionSocket.close();
} catch (IOException ex) {
Logger.getLogger(SThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
This code has a number of problems.
First off, in the future, please post smaller, concise code fragments that are well formatted. I just had to basically reformat everything in your post.
I see a couple of places where you are catching but doing nothing with exceptions. This is tremendously bad practice. At the least you should be printing/logging the exceptions you catch. I suspect this is contributing to your problems.
I find the RW_Flag very confusing. You should have two client threads then. One to write from System.in to the server and one to read. Don't have one client thread which does 2 things. Same with status flag in the server. That should be 2 different threads.
Instead of int flag = 0; in the server, that should be boolean loggedIn;. Make use of booleans in Java instead of C-style flags and use better variable names. The code readability will pay for itself. Same for status, RW_flag, etc..
Instead of huge code blocks, you should move contiguous code out to methods: handleSystemIn(), handleClient(), talkToServer(). Once you make more methods in the your code, and shrink down the individual code blocks, it makes it much more readable/debuggable/understandable.
You need to have a synchronized (tt) block around each usage of that array. Once you have multiple threads that are all using tt if the main accept thread adds to it, the updates need to be synchronized.
I don't immediately see the problem although the spagetti code is just too hard to parse. I suspect you are throwing and exception somewhere which is the reason why clients can't connect after the first one quits. Other than that, I would continue to use liberal use of System.out.println debugging to see what messages are being sent where.

How to optimize this web-server i am using with Java for rendering JPEG file only? Which is extream slow

When i use one jpeg image with this web-server its very slow to show the picture in the browser. But the same picture when i open using Apache web server its super fast.
What am i missing in my code which is so slow to render the jpeg file? Following is the code i am using:
server.java:
package www;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class server extends Thread
{
public server(int listen_port, webserver_starter to_send_message_to)
{
message_to = to_send_message_to;
port = listen_port;
this.start();
}
private void s(String s2)
{
message_to.send_message_to_window(s2);
}
private webserver_starter message_to;
private int port;
public void run()
{
ServerSocket serversocket = null;
s("The httpserver v. 0000000000\n\n");
try {
s("Trying to bind to localhost on port " + Integer.toString(port) + "...");
serversocket = new ServerSocket(port);
}catch (Exception e) {
s("\nFatal Error:" + e.getMessage());
System.exit(0);
return;
}
s("OK!\n");
while (true)
{
s("\nReady, Waiting for requests...\n");
try {
Socket connectionsocket = serversocket.accept();
InetAddress client = connectionsocket.getInetAddress();
s(client.getHostName() + " connected to server.\n");
BufferedReader input =
new BufferedReader(new InputStreamReader(connectionsocket.
getInputStream()));
DataOutputStream output =
new DataOutputStream(connectionsocket.getOutputStream());
http_handler(input, output);
} catch (Exception e) {
s("\nError:" + e.getMessage());
}
}
}
private void http_handler(BufferedReader input, DataOutputStream output)
{
int method = 0; //1 get, 2 head, 0 not supported
String http = new String(); //a bunch of strings to hold
String path = new String(); //the various things, what http v, what path,
String file = new String(); //what file
String user_agent = new String(); //what user_agent
try {
String tmp = input.readLine(); //read from the stream
String tmp2 = new String(tmp);
tmp.toUpperCase(); //convert it to uppercase
if (tmp.startsWith("GET")) { //compare it is it GET
method = 1;
} //if we set it to method 1
if (tmp.startsWith("HEAD")) { //same here is it HEAD
method = 2;
} //set method to 2
if (method == 0) {
try {
output.writeBytes(construct_http_header(501, 0));
output.close();
return;
}
catch (Exception e3) {
s("error:" + e3.getMessage());
}
}
int start = 0;
int end = 0;
for (int a = 0; a < tmp2.length(); a++) {
if (tmp2.charAt(a) == ' ' && start != 0) {
end = a;
break;
}
if (tmp2.charAt(a) == ' ' && start == 0) {
start = a;
}
}
path = tmp2.substring(start + 2, end);
}
catch (Exception e) {
s("errorr" + e.getMessage());
}
s("\nClient requested:" + new File(path).getAbsolutePath() + "\n");
FileInputStream requestedfile = null;
try {
requestedfile = new FileInputStream(path);
}
catch (Exception e) {
try {
output.writeBytes(construct_http_header(404, 0));
output.close();
}
catch (Exception e2) {}
;
s("error" + e.getMessage());
}
try {
int type_is = 0;
if (path.endsWith(".zip"))
{
type_is = 3;
}
if (path.endsWith(".jpg") || path.endsWith(".jpeg"))
{
type_is = 1;
}
if (path.endsWith(".gif"))
{
type_is = 2;
}
output.writeBytes(construct_http_header(200, 5));
if (method == 1)
{
while (true)
{
int b = requestedfile.read();
if (b == -1) {
break; //end of file
}
output.write(b);
}
}
output.close();
requestedfile.close();
}
catch (Exception e) {}
}
private String construct_http_header(int return_code, int file_type)
{
String s = "HTTP/1.0 ";
switch (return_code)
{
case 200:
s = s + "200 OK";
break;
case 400:
s = s + "400 Bad Request";
break;
case 403:
s = s + "403 Forbidden";
break;
case 404:
s = s + "404 Not Found";
break;
case 500:
s = s + "500 Internal Server Error";
break;
case 501:
s = s + "501 Not Implemented";
break;
}
s = s + "\r\n";
s = s + "Connection: close\r\n";
s = s + "Server: SimpleHTTPtutorial v0\r\n";
switch (file_type) {
case 0:
break;
case 1:
s = s + "Content-Type: image/jpeg\r\n";
break;
case 2:
s = s + "Content-Type: image/gif\r\n";
case 3:
s = s + "Content-Type: application/x-zip-compressed\r\n";
default:
//s = s + "Content-Type: text/html\r\n";
s = s + "Content-Type: image/jpeg\r\n";
break;
}
s = s + "\r\n";
return s;
}
}
Well here's the first thing I'd fix:
while (true)
{
int b = requestedfile.read();
if (b == -1) {
break; //end of file
}
output.write(b);
}
You're reading and writing a single byte at a time. That will be painfully slow. Read and write a whole buffer at a time instead:
byte[] buffer = new byte[32 * 1024]; // 32K is a reasonable buffer size
int bytesRead;
while ((bytesRead = requestedfile.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
}
There may well be other performance problems in your code - there are certainly a lot of things I'd change about it, including following Java naming conventions everywhere and certainly fixing this:
// You should basically *never* have this code
catch (Exception e){}
... but as you asked about the performance, that's the first bit I've checked for.

Java NIO multiple socket connections failing

I have a program that attempts to connect to port 80 on different machines and reports if there is a server running. I am using NIO which therefore uses sockets to do the connection. I do a connect and then poll using finishConnect().
I am getting inconsistent behaviour. Sometimes the program correctly reports that there are web servers running on the various machines that I am scanning. However at other times the connections do not get reported even though there are webservers running on the target machines.
I would understand this if I was using UDP sockets as these are not reliable but I am using a TCP connection that should be reliable i.e no dropped packets.
I need to be able to scan many machines but this inconsistent behaviour exhibits it self even when testing the program with just 4 target IP addresses that all have webservers on port 80.
TIA
Rod
class SiteFinder {
private static final long TIMEOUT = 500;
public void findSites() {
int numSocketChannels = 100;
int socketChannelCounter = 0;
long ipAddressCounter = 0;
boolean done = false;
List<String> allIpAddresses =
IPAddressGenerator.getIPAddresses(170);
SocketChannel[] socketChannelArray =
new SocketChannel[numSocketChannels];
Iterator<String> itr = allIpAddresses.iterator();
while(itr.hasNext()) {
int k;
for (k = 0; k < numSocketChannels && itr.hasNext(); k++) {
String ipAddress = itr.next();
ipAddressCounter++;
if (ipAddressCounter % 50000 == 0)
System.out.println(ipAddressCounter + " at " + new Date());
try {
socketChannelArray[k] = SocketChannel.open();
socketChannelArray[k].configureBlocking(false);
if (socketChannelArray[k].connect(
new InetSocketAddress(ipAddress,80))) {
System.out.println(
"connection established after connect() "
+ ipAddress);
socketChannelArray[k].close();
socketChannelArray[k] = null;
}
} catch (IOException ioe) {
System.out.println(
"error opening/connecting socket channel " + ioe);
socketChannelArray[k] = null;
}
}
while (k < numSocketChannels) {
socketChannelArray[k++] = null;
}
long startTime = System.currentTimeMillis();
long timeout = startTime + TIMEOUT;
connect:
while (System.currentTimeMillis() < timeout) {
//System.out.println("passing");
socketChannelCounter = 0;
for(int j = 0; j < socketChannelArray.length; j++) {
//System.out.println("calling finish connect");
if (socketChannelArray[j] == null) {
++socketChannelCounter;
if (socketChannelCounter == numSocketChannels) {
System.out.println("terminating connection loop");
break connect;
}
continue;
}
try {
if (socketChannelArray[j].finishConnect()) {
/*try {
out.write("connection established after " +
finishConnect()" +
clientChannelVector.elementAt(j).socket().
getInetAddress() + '\n');
out.flush();
} catch (IOException ioe) {
System.out.println(
"error writing to site-list "
+ ioe.getMessage());
}*/
System.out.println(
"connection established after finishConnect()"
+ socketChannelArray[j].socket().
getInetAddress());
socketChannelArray[j].close();
socketChannelArray[j] = null;
}
} catch (IOException ioe) {
System.out.println(
"error connecting from "
+ "clientChannel.finishConnect()");
try {
socketChannelArray[j].close();
} catch (IOException e) {
System.out.println("error closing socket channel");
} finally {
//System.out.println("removing socket channel");
//System.out.println(clientChannelVector.size());
socketChannelArray[j] = null;
}
}
}
}
closeConnections(socketChannelArray);
}
}
private void closeConnections(SocketChannel[] socketChannelArray) {
for (int i = 0; i < socketChannelArray.length; i++) {
if (socketChannelArray[i] == null) {
continue;
}
try {
socketChannelArray[i].close();
//System.out.println(
//"TIME OUT WAITING FOR RESPONSE CLOSING CONNECTION");
} catch (IOException ioe) {
System.out.println(
"error closing socket channel " + ioe.getMessage());
}
}
}
}

Categories

Resources