import java.io.*;
import java.net.*;
public class server
{ public static void main(String[] args)
{ int i=1;
try
{ ServerSocket s = new ServerSocket(27001); //establish a server
while(true)
{ Socket incoming = s.accept(); //waiting for "i" client
System.out.println(" Spawning " + i);
new ThreadedEchoHandler(incoming, i).start();
i++;
}
}
catch(Exception e)
{ System.out.println(e);
}
}
}
class ThreadedEchoHandler extends Thread
{ private Socket incoming;
private int counter;
public ThreadedEchoHandler(Socket i, int c)
{ incoming = i;
counter = c;
}
public void run()
{ try
{ BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter(incoming.getOutputStream(), true); //autoFlush
out.println("Hello! Enter 'x' for exit");
boolean done = false;
while(!done)
{ String str = in.readLine();
if(str == null) done = true;
else
{ out.println("Echo (" + counter + "): " + str);
if(str.trim().equals("x"))
done = true;
}
}
incoming.close();
}
catch(Exception e)
{ System.out.println(e);
}
}
}
[java] establishing client
I want to do simple multi-client server/client program.
I already done the server side, and I dont know how to make the client class. This is my multi-client server:
How can I create client ?
THANKS
Just write a second class that opens a Socket object pointing to the host and port that you specify the ServerSocket to listen on (for example, if you are running this on your own machine, point the client apps Socket object to 127.0.0.1 and port 27001).
Simple as that. Java Network Programming, 2nd Edition is a pretty good guide to all things java.net.*, so I would recommend grabbing a copy.
Simple as that. Java Network Programming, 2nd Edition is a pretty good guide to all things java.net.*, so I would recommend grabbing a copy.
I want my server to print the string client sending him. I dont understand why its not happening. This is my client:
import java.net.*;import java.io.*;public class client{ public static void main(String[] args) { try { Socket s = new Socket("", 27001); PrintWriter out = new PrintWriter(s.getOutputStream()); out.print("Server hello!"); } catch(Exception e) { System.out.println(e); } }}
You didn't give a host name for the client to connect to. If it is on your own machine then use localhost or 127.0.0.1
Use:
Then look at the stack trace. It will show line numbers in your code. Look at those lines to try and figure it out.
catch(IOException e) { e.printStackTrace();}
Then look at the stack trace. It will show line numbers in your code. Look at those lines to try and figure it out.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement