what i want to do is to create to start 2 tread of server in my class main server.... and each class server start a thread for each connection...
example server1 start with port 4444 and server2 with port 4445
all client connect to server1 except if the server is down...
my code
ServerMain class import java.net.*; import java.io.*;
public class ServerMain {
public static void main(String[] args) throws IOException { Server server1 = new Server(4444); Server server2 = new Server(4445); server1.start(); server2.start(); } }
Server class import java.net.*; import java.io.*;
public class Server extends Thread{
private static int nbRequest=0;
public synchronized int addRequest(){ return nbRequest++; }
public synchronized int getRequest(){ return nbRequest; }
public int port=0;
public Server(int port) { super("Server"); this.port = port; }
public void run() { ServerSocket serverSocket = null; Socket s=null; boolean listening = true; try { serverSocket = new ServerSocket(port); s=serverSocket.accept(); } catch (IOException e) { System.err.println("Could not listen on port."); System.exit(-1); } System.out.println("server run, wait connecting...."); while (listening) new ServerThread(s).start();
try { System.out.println("connexion successfull"); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream()));
client class i need to add function to be able to try during 10 second to connect to server 1(4444).... i the server don't respond... i try to connect to server2 (port 4445) import java.io.*; import java.net.*; import java.lang.*;
public class Client { public static void main(String[] args) throws IOException { String serverHostname = new String ("127.0.0.1"); int port=4444 System.out.println ("Essai de se connecter a l'hote " + serverHostname + " au port. " + port); Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket(serverHostname, port); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Hote inconnu: " + serverHostname); System.exit(1); } catch (IOException e) { System.err.println("Ne pas se connecter au serveur: " + serverHostname); System.exit(1); }