Skip to content

Instantly share code, notes, and snippets.

@Korilakkuma
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save Korilakkuma/6c437aea10894f6aefb5 to your computer and use it in GitHub Desktop.

Select an option

Save Korilakkuma/6c437aea10894f6aefb5 to your computer and use it in GitHub Desktop.
Chat Client
import java.io.*;
import java.net.*;
public final class ChatClient {
private static final String SERVER_HOST = "localhost";
private static final String TERMINAL_MESSAGE = "quit";
private static final int BUFFER_SIZE = 4096;
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Port number must be designated !!");
System.exit(1);
}
Socket socket = null;
try {
socket = new Socket(ChatClient.SERVER_HOST, Integer.parseInt(args[0]));
while (true) {
Reader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Writer output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//for Receive Message
StringBuilder sb = new StringBuilder(ChatClient.BUFFER_SIZE);
System.out.print("Send Message >> ");
Reader stdin = new BufferedReader(new InputStreamReader(System.in));
char[] buffer = new char[ChatClient.BUFFER_SIZE];
while (stdin.read(buffer) != -1) {
//Send
output.write(buffer);
String message = String.valueOf(buffer); //String message = new String(buffer, 'UTF-8');
if (message.trim().toLowerCase().equals(ChatClient.TERMINAL_MESSAGE)) {
System.out.println("Quit Chat. Good Bye !!");
System.exit(0);
} else if (message.indexOf("\n") != -1) {
break;
}
}
output.write('\n');
output.flush();
System.out.println("Waiting ...");
int c = 0;
while ((c = input.read()) != -1) {
if (c == '\n') {
break;
}
sb.append((char)c);
}
if (sb.toString().trim().toLowerCase().equals(ChatClient.TERMINAL_MESSAGE) || sb.toString().trim().equals("")) {
System.out.println("Quit Chat. Good Bye !!");
break;
} else {
System.out.println("Receive Message >> " + sb.toString());
}
}
} catch (UnknownHostException error) {
error.printStackTrace();
} catch (IOException error) {
error.printStackTrace();
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException error) {
error.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment