Creating a simple Chat Client/Server Solution – Part1

Standard

Here is an example of how to extend a very simple client-server demo program into a fully functioning (but simple) Chat Client/Server package. There are five stages involved:

Step 1: A simple server that will accept a single client connection and display everything the client says on the screen. If the client user types “.bye”, the client and the server will both quit.
Step 2: A server as before, but this time it will remain ‘open’ for additional connection once a client has quit. The server can handle at most one connection at a time.
Step 3: A server as before, but this time it can handle multiple clients simultaneously. The output from all connected clients will appear on the server’s screen.
Step 4: A server as before, but this time it sends all text received from any of the connected clients to all clients. This means that the server has to receive and send, and the client has to send as well as receive
Step 5: Wrapping the client from step 4 into a very simple GUI interface but not changing the functionality of either server or client. The client is implemented as an Applet, but a Frame would have worked just as well (for a stand-alone program).

Step 1: Simple, one-time Server

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

public class ChatServer
{  private Socket          socket   = null;
private ServerSocket    server   = null;
private DataInputStream streamIn =  null;

public ChatServer(int port)
{  try
{  System.out.println(“Binding to port ” + port + “, please wait  …”);
server = new ServerSocket(port);
System.out.println(“Server started: ” + server);
System.out.println(“Waiting for a client …”);
socket = server.accept();
System.out.println(“Client accepted: ” + socket);
open();
boolean done = false;
while (!done)
{  try
{  String line = streamIn.readUTF();
System.out.println(line);
done = line.equals(“.bye”);
}
catch(IOException ioe)
{  done = true;
}
}
close();
}
catch(IOException ioe)
{  System.out.println(ioe);
}
}
public void open() throws IOException
{  streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{  if (socket != null)    socket.close();
if (streamIn != null)  streamIn.close();
}
public static void main(String args[])
{  ChatServer server = null;
if (args.length != 1)
System.out.println(“Usage: java ChatServer port”);
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}

The Simple Client corresponding to the previous server (and to step 2 and step 3 servers as well):

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

public class ChatClient
{  private Socket socket              = null;
private DataInputStream  console   = null;
private DataOutputStream streamOut = 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());
}
String line = “”;
while (!line.equals(“.bye”))
{  try
{  line = console.readLine();
streamOut.writeUTF(line);
streamOut.flush();
}
catch(IOException ioe)
{  System.out.println(“Sending error: ” + ioe.getMessage());
}
}
}
public void start() throws IOException
{  console   = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void stop()
{  try
{  if (console   != null)  console.close();
if (streamOut != null)  streamOut.close();
if (socket    != null)  socket.close();
}
catch(IOException ioe)
{  System.out.println(“Error closing …”);
}
}
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]));
}
}

Nguồn: Sưu tầm

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