import java.net.*;
class Servidor implements Runnable {
private ServerSocket ss;
private Thread thread;
int nc;
Servidor(int puerto) {
try{
ss = new ServerSocket(puerto);
nc = 0;
thread = new Thread(this,"servidor");
thread.start();
System.out.println("Servidor listo");
}catch(Exception e) {
e.printStackTrace();
}
}
public void run() {
while(true) {
try{
new Conexion(ss.accept(),++nc);
}catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Servidor(200);
}
}
class Conexion implements Runnable {
private Socket socket;
private Thread thread;
private BufferedReader br;
private PrintWriter pw;
private File file;
Conexion(Socket s,int n) {
try{
socket = s;
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
file = new File("Cliente"+n);
pw = new PrintWriter(new FileWriter(file));
thread = new Thread(this,"Conexion"+n);
thread.start();
System.out.println("Nueva conéxion lista");
}catch(Exception e) {
e.printStackTrace();
}
}
public void run() {
try{
while(socket.isConnected()) {
String s = br.readLine();
System.out.println(s);
pw.println(s);
pw.flush();
}
br.close();
pw.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
public class Cliente implements Runnable {
private Socket socket;
private PrintWriter pw;
private BufferedReader br;
private Thread thread;
public Cliente() {
try{
socket = new Socket("localhost",200);
pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
br = new BufferedReader(new InputStreamReader(System.in));
thread = new Thread(this);
thread.start();
}catch(Exception e) {
e.printStackTrace();
}
}
public void run() {
while(true) {
try{
pw.println(br.readLine());
}catch(Exception e) {
e.printStackTrace();
}
}
}
/**
* Method main
*
*
* @param args
*
*/
public static void main(String[] args) {
// TODO: Add your code here
new Cliente();
}
}