It is an "echo" server where I want that when two clients connect, they send a String to the server, the latter answers and the client prints the read.
The fact is that one of them is left unanswered, I use Threads on the server for each client that connects.
Client:
public class Client {
protected Socket sk;
public DataOutputStream out;
public DataInputStream in;
public Boolean exit=false;
public Client(String addr, int port) {
try {
sk = new Socket(addr, port);
} catch (Exception e) {
System.err.println("Cli Socket"+e);
}
}
public void readLines(){
String line;
Mess m=null;
Scanner sc = new Scanner(System.in);
try {
in= new DataInputStream(sk.getInputStream());
out = new DataOutputStream(sk.getOutputStream());
System.out.print(">>");
while((line=sc.nextLine()).equals("quit")!= true){
out.writeUTF(line);
System.out.println(in.readUTF());
}
} catch (Exception e) {
System.err.println("Cli readlnes:"+e);
sc.close();
}finally {
try {
if (sc != null) {
sc.close();
}
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (sk != null) {
sk.close();
}
} catch (IOException e1) {
System.out.println("Conexión finalizada");
e1.printStackTrace();
}
}
}
Server:
public class Server {
public ServerSocket sk;
protected int port;
public DataInputStream in;
public DataOutputStream out;
public Server(int port){
this.port=port;
try {
sk= new ServerSocket(port);
} catch (Exception e) {
System.err.println("Server"+e);
}
}
public void serve(){
while(true){
try {
System.out.println("Waiting....");
final Socket csk = sk.accept();
new Thread(){
public void run() { serveClient(csk); }
}.start();
System.out.println("Accept connection.."+csk.getLocalAddress()+" "+csk.getPort());
} catch (Exception e) {
System.err.println("Srv serve"+e);
}
}
}
public void serveClient(Socket sk){
String result=null;
Mess m;
boolean exit = false;
try {
out=new DataOutputStream(sk.getOutputStream());
in= new DataInputStream(sk.getInputStream());
while(!exit){
result=in.readUTF();
out.writeUTF(result);
}
} catch (Exception e) {
System.err.println("Servecli "+e);
}
}