Pergunta

i have a simple server...

public static void main(String[] args) throws Exception{
    ServerSocket server = new ServerSocket(2000);
    Socket sock = server.accept();
    InputStream  in = sock.getInputStream();
    OutputStream out = sock.getOutputStream();
    PrintWriter w = new PrintWriter(out);
    Scanner s = new Scanner(in);
    ...

and a simple client...

public static void main(String[] args) throws Exception{
    Socket sock = new Socket("localhost",2000);;
    InputStream in= sock.getInputStream();
    OutputStream out = sock.getOutputStream();
    PrintWriter w  = new PrintWriter(out);
    Scanner s = new Scanner(in);
    ....

-how can i connect more clients to this server? (I need 2 more) -also i want to send system time from server to clients and then clients will send back their time 10 times each plus some fixed delay (0.5-1 sec) then the server must find the average from all delays and send it back to the clients as the new time...

thank you for your time...

Foi útil?

Solução

System.currentTimeMillis() provides the system time

Every Socket returned by server.accept() is a separate object and your server can communicate independently with each client through each Socket object. However, since your application is time-sensitive, I would recommend using a separate thread for each client.

A simple server would be:

ServerSocket serverSock = new ServerSocket(2000);

while (true)
{
    Socket fpSock = serverSock.accept();
    MyThread t = new MyThread(fpSock, this);
    t.start();
}

The processing you need will be done in the MyThread run() method. "this" is passed to the thread to provide a reference where each thread can callback to methods in the main class. Make sure to make such methods synchronized.

You also don't necessarily need to send the server's time to the client, simply send a generic packet which the client is expected to echo back. Use the server's timestamp for all transactions to avoid variation in client system time.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top