Java Chat Server Tutorial

Chat servers traditionally allow two or more users to communicate one-on-one through textual messages on their computers. Essentially, a chat server listens for incoming messages and sends outgoing messages. In Java, you can create a Chat Server class that takes user-defined input and output streams already assigned to serial sports, listens for incoming messages from another computer and sends outgoing messages created by the user.

Things You'll Need

  • Java Development Kit (JDK)
Show More

Instructions

    • 1

      Set up basic chat client and function definitions:

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

      public class ChatClient extends Frame implements Runnable {
      public ChatClient (String title, InputStream i, OutputStream o) {}
      public void run () {}
      public static void sendMessage(String msg){}
      }

    • 2

      Set up basic client and thread listener as the class constructor. This constructor takes an input (variable "i") and output stream (variable "o"), converts them to buffered data streams and starts a listening thread to wait for messages:

      //ChatClient class variables
      protected DataInputStream i;
      protected DataOutputStream o;
      protected Thread listener;

      public ChatClient(InputStream i, OutputStream o){
      this.i = new DataInputStream (new BufferedInputStream (i))
      this.o = new DataOutputStream (new BufferedOutputStream (o));
      listener = new Thread (this);
      listener.start ();
      }

    • 3

      Define the "run" method, which executes when the listener thread begins. This method checks the input data stream, appends any incoming data to the "received" string and terminates when the connection closes.

      public void run () {

      String received = new String();

      try {
      while (true) {
      String incoming = i.readUTF ();
      received += (line + "\n");
      }
      } catch (IOException e) {
      e.printStackTrace ();
      }
      }

    • 4

      Define a "sendMessage" function, which will send data over the output connection in the form of a string:

      public void sendMessage(String msg){
      o.writeUTF (msg);
      o.flush ();
      } catch (IOException ex) {
      ex.printStackTrace();
      listener.stop ();
      }
      }

Tips & Warnings

  • This is only a skeleton model of a possible chat server implementation. Other functionality such as GUI interfaces, images, or other chat monitoring tools can be added.

Related Searches:

References

Comments

Related Ads

Featured