Suppose I have 4 clients having port num 1,2,3,4 respectively and one server.
I want to make a connection between server and client and then send clients name and ipaddress to server and simple read that string on server.
In server side socket programming I have used a for loop to access respective clients on port 1,2,3,4.
Now my question is when the client on portnum 2 is not active, server should wait for 1 second and then move to next port num 3 but it is happening so server is stuck in that loop until it makes a connection to portnum 2.
I have used setSoTimeout function but still problem isn't resolved.
Kindly help me
Server Side code is
package server;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable {
Socket csocket;
Server(Socket csocket) {
this.csocket = csocket;
}
public static void main(String args[])
throws Exception {
for (int i=1; i<=4; i++) {
ServerSocket ssock = new ServerSocket(i);
System.out.println("Listening");
//while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new Server(sock)).start();
}
}
public void run() {
try {
DataInputStream dis = new DataInputStream(csocket.getInputStream());
String str=dis.readUTF();
System.out.print(str);
dis.close();
csocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
Client side code is
package client;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client
{
Socket s;
DataOutputStream dout;
public Client() {
while(true)
try {
s=new Socket("192.168.1.101",1);
dout= new DataOutputStream(s.getOutputStream());
java.net.InetAddress j = java.net.InetAddress.getLocalHost();
dout.writeUTF(j.getHostName()+"\t\t\t"+j.getHostAddress());
//Userinfo();
}
catch(Exception e)
{
System.out.println(e);
}
}
// public void Userinfo() throws UnknownHostException, IOException
// {
//
//
// }
public static void main(String as[])
{
new Client();
}
}