/*
* Socket and runnable implement multi-person access server
* Because each connection starts a new thread, multiple customers can connect to the server at the same time.
* Basic operating procedures are as follows:
* 1) programming and running server programs
* 2) Open multiple Telnet windows
* 3) Switch between these windows and type the command. Note that you can communicate through these windows at the same time.
* 4) When this is done, switch to the program window where you started the server and use CTRL + C to forcibly close it
* */
Package threaded;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import Java.util.Scanner;
public class Threadedechoserver {
public static void Main (string[] args) {
TODO auto-generated Method Stub
try{
int i = 1;
ServerSocket s = new ServerSocket (8189);
while (true) {
Socket incoming = S.accept ();
System.out.println ("spawning" + i);
Runnable r = new Threadedechohandler (incoming);
Thread t = new Thread (r);
i++;
}
}catch (IOException e) {
E.printstacktrace ();
}
}
}
Class Threadedechohandler implements runnable{
Private Socket incoming;
Public Threadedechohandler (Socket i) {
incoming = i;
}
public void Run () {
try{
try{
InputStream instream = Incoming.getinputstream ();
OutputStream OutStream = Incoming.getoutputstream ();
Scanner in = new Scanner (instream);
PrintWriter out = new PrintWriter (OutStream, true);
Out.println ("Hello Enter BYE to exit");
Boolean done = false;
while (!done && in.hasnextline ()) {
String line = In.nextline ();
Out.println ("Echo:" + line);
if (Line.trim (). Equals ("BYE")) {
Done = true;
}
}
}finally{
Incoming.close ();
}
}catch (IOException e) {
E.printstacktrace ();
}
}
}
Sockets and runnable implement multi-person access servers