Creating a simple Chat Client/Server Solution – Part4

Standard

Step 4: A Simple but functional, text based chat server/client

import java.net.*;
import java.io.*;

public class ChatServer implements Runnable
{  private ChatServerThread clients[] = new ChatServerThread[50];
private ServerSocket server = null;
private Thread       thread = null;
private int clientCount = 0;

public ChatServer(int port)
{  try
{  System.out.println(“Binding to port ” + port + “, please wait  …”);
server = new ServerSocket(port);
System.out.println(“Server started: ” + server);
start(); }
catch(IOException ioe)
{  System.out.println(“Can not bind to port ” + port + “: ” + ioe.getMessage()); }
}
public void run()
{  while (thread != null)
{  try
{  System.out.println(“Waiting for a client …”);
addThread(server.accept()); }
catch(IOException ioe)
{  System.out.println(“Server accept error: ” + ioe); stop(); }
}
}
public void start()  { /* as before */ }
public void stop()   { /* as before */ }
private int findClient(int ID)
{  for (int i = 0; i < clientCount; i++)
if (clients[i].getID() == ID)
return i;
return -1;
}
public synchronized void handle(int ID, String input)
{  if (input.equals(“.bye”))
{  clients[findClient(ID)].send(“.bye”);
remove(ID); }
else
for (int i = 0; i < clientCount; i++)
clients[i].send(ID + “: ” + input);
}
public synchronized void remove(int ID)
{  int pos = findClient(ID);
if (pos >= 0)
{  ChatServerThread toTerminate = clients[pos];
System.out.println(“Removing client thread ” + ID + ” at ” + pos);
if (pos < clientCount-1)
for (int i = pos+1; i < clientCount; i++)
clients[i-1] = clients[i];
clientCount–;
try
{  toTerminate.close(); }
catch(IOException ioe)
{  System.out.println(“Error closing thread: ” + ioe); }
toTerminate.stop(); }
}
private void addThread(Socket socket)
{  if (clientCount < clients.length)
{  System.out.println(“Client accepted: ” + socket);
clients[clientCount] = new ChatServerThread(this, socket);
try
{  clients[clientCount].open();
clients[clientCount].start();
clientCount++; }
catch(IOException ioe)
{  System.out.println(“Error opening thread: ” + ioe); } }
else
System.out.println(“Client refused: maximum ” + clients.length + ” reached.”);
}
public static void main(String args[]) { /* as before */ }
}
import java.net.*;
import java.io.*;

public class ChatServerThread extends Thread
{  private ChatServer       server    = null;
private Socket           socket    = null;
private int              ID        = -1;
private DataInputStream  streamIn  =  null;
private DataOutputStream streamOut = null;

public ChatServerThread(ChatServer _server, Socket _socket)
{  super();
server = _server;
socket = _socket;
ID     = socket.getPort();
}
public void send(String msg)
{   try
{  streamOut.writeUTF(msg);
streamOut.flush();
}
catch(IOException ioe)
{  System.out.println(ID + ” ERROR sending: ” + ioe.getMessage());
server.remove(ID);
stop();
}
}
public int getID()
{  return ID;
}
public void run()
{  System.out.println(“Server Thread ” + ID + ” running.”);
while (true)
{  try
{  server.handle(ID, streamIn.readUTF());
}
catch(IOException ioe)
{  System.out.println(ID + ” ERROR reading: ” + ioe.getMessage());
server.remove(ID);
stop();
}
}
}
public void open() throws IOException
{  streamIn = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
streamOut = new DataOutputStream(new
BufferedOutputStream(socket.getOutputStream()));
}
public void close() throws IOException
{  if (socket != null)    socket.close();
if (streamIn != null)  streamIn.close();
if (streamOut != null) streamOut.close();
}
}


import java.net.*;
import java.io.*;

public class ChatClient implements Runnable
{  private Socket socket              = null;
private Thread thread              = null;
private DataInputStream  console   = null;
private DataOutputStream streamOut = null;
private ChatClientThread client    = null;

public ChatClient(String serverName, int serverPort)
{  System.out.println(“Establishing connection. Please wait …”);
try
{  socket = new Socket(serverName, serverPort);
System.out.println(“Connected: ” + socket);
start();
}
catch(UnknownHostException uhe)
{  System.out.println(“Host unknown: ” + uhe.getMessage()); }
catch(IOException ioe)
{  System.out.println(“Unexpected exception: ” + ioe.getMessage()); }
}
public void run()
{  while (thread != null)
{  try
{  streamOut.writeUTF(console.readLine());
streamOut.flush();
}
catch(IOException ioe)
{  System.out.println(“Sending error: ” + ioe.getMessage());
stop();
}
}
}
public void handle(String msg)
{  if (msg.equals(“.bye”))
{  System.out.println(“Good bye. Press RETURN to exit …”);
stop();
}
else
System.out.println(msg);
}
public void start() throws IOException
{  console   = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
if (thread == null)
{  client = new ChatClientThread(this, socket);
thread = new Thread(this);
thread.start();
}
}
public void stop()
{  if (thread != null)
{  thread.stop();
thread = null;
}
try
{  if (console   != null)  console.close();
if (streamOut != null)  streamOut.close();
if (socket    != null)  socket.close();
}
catch(IOException ioe)
{  System.out.println(“Error closing …”); }
client.close();
client.stop();
}
public static void main(String args[])
{  ChatClient client = null;
if (args.length != 2)
System.out.println(“Usage: java ChatClient host port”);
else
client = new ChatClient(args[0], Integer.parseInt(args[1]));
}
}
import java.net.*;
import java.io.*;

public class ChatClientThread extends Thread
{  private Socket           socket   = null;
private ChatClient       client   = null;
private DataInputStream  streamIn = null;

public ChatClientThread(ChatClient _client, Socket _socket)
{  client   = _client;
socket   = _socket;
open();
start();
}
public void open()
{  try
{  streamIn  = new DataInputStream(socket.getInputStream());
}
catch(IOException ioe)
{  System.out.println(“Error getting input stream: ” + ioe);
client.stop();
}
}
public void close()
{  try
{  if (streamIn != null) streamIn.close();
}
catch(IOException ioe)
{  System.out.println(“Error closing input stream: ” + ioe);
}
}
public void run()
{  while (true)
{  try
{  client.handle(streamIn.readUTF());
}
catch(IOException ioe)
{  System.out.println(“Listening error: ” + ioe.getMessage());
client.stop();
}
}
}
}

Nguồn: sưu tầm

One thought on “Creating a simple Chat Client/Server Solution – Part4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s