//Server.java
import java.net.*;
import java.io.*;
public class Server{
public static void main(String[] args)throws IOException {
ServerSocket ss=new ServerSocket(8899);
try{
while(true){
System.out.println("Listening on port 8899...");
Socket so=ss.accept();
new ServerThread(so).start();
}
}catch(Exception e){System.err.println(e);}
finally{
try{
ss.close();
}catch(Exception e){
System.err.println("ServerSocket not closeed!");
}
}
}
}
class ServerThread extends Thread{
private Socket so;
public ServerThread(Socket s){
so=s;
}
public void run(){
try{
BufferedReader in=new BufferedReader(new InputStreamReader(so.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(so.getOutputStream())),true);
String str;
while((str=in.readLine())!=null){
System.out.println("Got message: "+str);
out.println("Server got it: "+str);
}
}catch(Exception e){System.err.println(e);}
}
}
//Client.java
import java.net.*;
import java.io.*;
public class Client extends Thread {
public void run() {
try {
InetAddress adds = InetAddress.getByName(null);
Socket so = new Socket(adds, 8899);
BufferedReader in = new BufferedReader(new InputStreamReader(so
.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(so.getOutputStream())), true);
int i = 0;
while (true) {
Thread.sleep(100);
out.println("Hello, MOTO " + ++i);
String str = in.readLine();
System.out.println("Got return message: " + str);
}
} catch (Exception e) {
} finally {
System.out.println("Over :=)");
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Client c = new Client();
c.start();
}
}
}