Skip to content

Instantly share code, notes, and snippets.

@tacksoo
Created February 7, 2013 20:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save tacksoo/4733928 to your computer and use it in GitHub Desktop.
Save tacksoo/4733928 to your computer and use it in GitHub Desktop.
Simple chat server/client example
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ChatClient implements Runnable {
// why is the ChatClient Multi-threaded?
private Socket link;
private PrintWriter outputStream;
private Scanner inputStream;
private int port = 7777;
private String nick;
public ChatClient() throws IOException {
initialize();
}
private void initialize() throws IOException {
// get server address
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the chat server's ip address?");
String str = keyboard.next();
// get user nick
System.out.println("What is your nick?");
nick = keyboard.next();
// connect to server
InetAddress host = null;
try {
host = InetAddress.getByName(str);
} catch (UnknownHostException e1) {
System.out.println("Host not found");
}
System.out
.println("You are now connected to: " + host.getHostAddress());
link = null;
try {
link = new Socket(host, port);
link.setReuseAddress(true);
} catch (IOException e) {
e.printStackTrace();
System.out.println("not found");
}
inputStream = new Scanner(link.getInputStream());
outputStream = new PrintWriter(link.getOutputStream());
// start new thread to listen from server
// one runnable, two threads... in which cases is this legal?
Thread t = new Thread(this);
t.start();
// continuously listen your user input
while (keyboard.hasNextLine()) {
String msg = keyboard.nextLine();
outputStream.println(nick + " says: " + msg);
outputStream.flush();
}
}
public static void main(String[] args) throws Exception {
new ChatClient();
}
@Override
public void run() {
while (true) {
if (inputStream.hasNextLine())
System.out.println(inputStream.nextLine());
}
}
}
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class ChatClientHandler implements Runnable {
// runnable for each client thread
private Socket client;
private ChatServer server;
private Scanner inputStream;
public ChatClientHandler(Socket client, ChatServer server) {
this.client = client;
this.server = server;
}
@Override
public void run() {
try {
inputStream = new Scanner(client.getInputStream());
while(true)
{
if(!inputStream.hasNext())
return;
String chatLine = inputStream.nextLine();
System.out.println(client.getRemoteSocketAddress() + " said: " + chatLine);
server.sendChatMessageToAll(chatLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
public class ChatServer {
// Toy ChatServer to illustrate multi-threading
private final int port = 7777;
private ServerSocket serverSocket;
private ArrayList<Socket> clientList;
public ChatServer() {
try {
serverSocket = new ServerSocket(port);
serverSocket.setReuseAddress(true);
} catch (IOException e)
{
System.out.println(e.getStackTrace());
}
clientList = new ArrayList<Socket>();
}
public void startServer() throws IOException {
System.out.println("Accepting clients...");
while(true)
{
// wait for a client
Socket client = serverSocket.accept();
clientList.add(client);
System.out.println("New client accepted..." + client.getRemoteSocketAddress());
System.out.println("Total users: " + clientList.size());
ChatClientHandler handler = new ChatClientHandler(client,this);
Thread t = new Thread(handler);
t.start();
}
}
public synchronized void sendChatMessageToAll(String msg) throws IOException {
for(Iterator<Socket> it=clientList.iterator(); it.hasNext();)
{
Socket client = it.next();
if( !client.isClosed() )
{
PrintWriter pw = new PrintWriter(client.getOutputStream());
pw.println(msg);
pw.flush();
//System.out.println("Sent to: " + client.getRemoteSocketAddress());
}
}
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
new ChatServer().startServer();
}
}
import java.net.InetAddress;
import java.net.UnknownHostException;
public class PrintInetAddress {
public static void main(String[] args) throws UnknownHostException {
System.out.println(InetAddress.getLocalHost().getHostAddress());
System.out.println(InetAddress.getLocalHost().getHostName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment