package com.j256.ormlite;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClient {
private static int port = 8001;
private static String host = "localhost";
private static BufferedReader stdIn;
public static void main(String[] args) throws IOException {
Socket server = null;
try {
server = new Socket(host, port);
} catch (UnknownHostException e) {
System.err.println(e);
System.exit(1);
}
stdIn = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(server.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
System.out.print("Autore: ");
String auth = stdIn.readLine();
out.println("Autore: " + auth);
String serverResponse = in.readLine();
System.out.println(serverResponse);
if (serverResponse.startsWith("SERVER: Benvenuto")) {
/* create a thread to asyncronously read messages from the server */
ServerConn sc = new ServerConn(server);
Thread t = new Thread(sc);
t.start();
/* loop reading messages from stdin and sending them to the server */
System.out.println("Reading from stdin");
while (true) {
String msg = stdIn.readLine();
if (msg == null || msg.equals("quit")) {
break;
}
System.out.println("Read from stdin: " + msg);
out.println(msg);
}
System.out.println("Exit.");
server.close();
} else {
System.out.println("Exit.");
System.out.println("---Client Error---");
}
}
private static class ServerConn implements Runnable {
private BufferedReader in = null;
private Socket server;
public ServerConn(Socket s) throws IOException {
server = s;
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
public void run() {
try {
/*
* loop reading messages from the server and show them on stdout
*/
while (true) {
String msg = in.readLine();
if (msg == null || msg.equals("quit")) {
break;
}
System.out.println(msg);
}
System.out.println("Closing server reader");
this.close();
} catch (IOException e) {
System.err.println(e);
}
}
public void close() throws IOException {
in.close();
server.close();
}
}
}