Web version Online chat Java socket implementation _java

Source: Internet
Author: User
Tags flush gettext pack socket

This article for you to share an online web page to meet the needs of the example, due to the Java socket implementation of the Web version of the online chat function for your reference, the specific content as follows

Implementation steps:
1, the use of AWT components and sockets to achieve a simple single client to the server to continue to send messages;
2, the combination of threads, the implementation of multiple client connection server to send messages;
3, the implementation of server-side forwarding client messages to all clients, while at the client display;
4, the AWT component generated by the window interface to the front-end JSP or HTML display interface, Java socket implementation of the client to the front-end technology implementation.

Here is the first step to achieve the simple function, the difficulty is:
1, no use of AWT components, no use of Java-related monitoring events;
2, long time does not use the socket to carry on the client and the service side the interaction, and has not really carried on the CS structure the development.

code to implement functionality :
Online chat client:
1, the formation of graphics window interface profile
2. Add Shutdown event for profile
3. Add input area and content display area in contour
4. Add carriage return event for input area
5, set up a service-side connection and send data

Package chat.chat; 
Import Java.awt.BorderLayout; 
Import Java.awt.Frame; 
Import Java.awt.TextArea; 
Import Java.awt.TextField; 
Import java.awt.event.ActionEvent; 
Import Java.awt.event.ActionListener; 
Import Java.awt.event.WindowAdapter; 
Import java.awt.event.WindowEvent; 
Import Java.io.DataOutputStream; 
Import java.io.IOException; 
Import Java.net.Socket; 
 
Import java.net.UnknownHostException;  
 /** * Online chat client 1, Generate graphics window interface Outline 2, add close event for Contour 3, include input area and content display area 4 in contour, add carriage return event for input area * 5, establish service-side connection and send data * * @author tuzongxun123 
  * */public class ChatClient extends Frame {//user input area private TextField tftxt = new TextField (); 
  Content display area private TextArea Tarea = new TextArea (); 
  Private socket socket = NULL; 
 
  Data output stream private dataoutputstream dataoutputstream = null; 
  public static void Main (string[] args) {new ChatClient (). Launcframe (); /** * Create a simple graphical window * * @author: Tuzongxun * @Title: Launcframe * @param * @return void
   * @date May, 2016 9:57:00 AM * @throws/public void Launcframe () {setlocation (300, 200); 
    This.setsize (200, 400); 
    Add (Tftxt, Borderlayout.south); 
    Add (Tarea, Borderlayout.north); 
    Pack (); The Shutdown Event This.addwindowlistener (new Windowadapter () {@Override public void windowclosing (Win 
        Dowevent e) {system.exit (0); 
      DisConnect (); 
    } 
    }); 
    Tftxt.addactionlistener (New Tflister ()); 
    SetVisible (TRUE); 
  Connect ();  /** * Connect Server * * @author: Tuzongxun * @Title: Connect * @param * @return void * @date May 2016 9:56:49 AM * @throws/public void Connect () {try {//new server connection socket = new sock 
      ET ("127.0.0.1", 8888); 
      Gets the client output stream dataoutputstream = new DataOutputStream (Socket.getoutputstream ()); 
    System.out.println ("connected to the service end"); 
    catch (Unknownhostexception e) {e.printstacktrace (); } CatCH (ioexception e) {e.printstacktrace ();  /** * Close Client Resource * * @author: Tuzongxun * @Title: DisConnect * @param * @return void * @date May, 2016 9:57:46 AM * @throws/public void DisConnect () {try {Dataoutputstream.close 
      (); 
    Socket.close (); 
    catch (IOException e) {e.printstacktrace (); }/** * Send message to Server * * @author: Tuzongxun * @Title: SendMessage * @param @param text * @ret 
      urn void * @date May, 2016 9:57:56 AM * @throws/private void SendMessage (String text) {try { 
      Dataoutputstream.writeutf (text); 
    Dataoutputstream.flush (); 
    catch (IOException E1) {e1.printstacktrace (); }/** * Graphics window Input Area Monitor carriage return event * * @author tuzongxun123 */Private class Tflister implements Ac Tionlistener {@Override public void actionperformed (ActionEvent e) {String text = Tftxt. GetText (). Trim (); 
      Tarea.settext (text); 
      Tftxt.settext (""); 
    Send data to server after carriage SendMessage (text); 
 } 
  } 
}

Service side:

Package chat.chat; 
Import Java.io.DataInputStream; 
Import java.io.EOFException; 
Import java.io.IOException; 
Import java.net.BindException; 
Import Java.net.ServerSocket; 
 
Import Java.net.Socket; /** * Java uses socket and AWT components to simply implement the online chat function server can implement a client-side connection and continuously send messages to the server * but not multiple clients are connected at the same time, because in the code to get the client connection will be repeatedly listening to the client input, causing blocking * so that clothing The server can not two times listen to another client, if you want to implement, you need to use asynchronous or multi-threaded * * @author tuzongxun123 */public class Chatserver {public static void M 
    Ain (string[] args) {//whether the server is successfully started Boolean isstart = false; 
    Service-side SOCKET ServerSocket SS = NULL; 
    Client socket SOCKET sockets = NULL; 
    The service side reads the client data input stream DataInputStream datainputstream = null; 
    try {//start server SS = new ServerSocket (8888); 
      catch (Bindexception e) {System.out.println ("port is already in use"); 
    Close Program System.exit (0); 
    catch (Exception e) {e.printstacktrace (); 
      try {Isstart = true; while (Isstart) {Boolean isconnect = false; 
        Start listening socket = Ss.accept (); 
        SYSTEM.OUT.PRINTLN ("One client Connect"); 
        Isconnect = true; while (isconnect) {//Get client input stream datainputstream = new DataInputStream (Socket.getinpu 
          Tstream ()); 
          Reads the data sent by the client String message = Datainputstream.readutf (); 
        SYSTEM.OUT.PRINTLN ("Client said:" + message); 
    The catch (Eofexception e) {System.out.println ("client closed!"); 
    catch (Exception e) {e.printstacktrace (); 
        Finally {//close related resources try {datainputstream.close (); 
      Socket.close (); 
      catch (IOException e) {e.printstacktrace (); 
 } 
    } 
  } 
}

Continue, on the basis of a single client connection, the second step here is to implement a multiple-client connection and need to use the thread. Each time a new client connects, the server needs to start a new thread to handle the problem of blocking in the previous loop read.

There are usually two ways to write threads, integrating thread or implementing the Runnable interface, which is not inherited in principle when implementing runnable, because the way to implement the interface is more flexible.

The client code has not changed before, becoming a server, so there is only a service-side code posted here:

Java uses socket and AWT components as well as multithreading simple implementation of online chat function server:

When multiple client connections are implemented, messages are sent continuously to the server, with the emphasis on multithreading in relation to the first version. The service side has not implemented forwarding function, the Client graphics window can only see the information that they entered and cannot see the messages sent by other clients.

Package chat.chat; 
Import Java.io.DataInputStream; 
Import java.io.EOFException; 
Import java.io.IOException; 
Import java.net.BindException; 
Import Java.net.ServerSocket; 
Import Java.net.Socket; 
 
Import java.net.SocketException; 
    /** * * * * @author tuzongxun123 * */public class Chatserver {public static void main (string[] args) { 
  New Chatserver (). Start (); 
  }//Whether the server is successfully started private Boolean isstart = false; 
  Server Socket PRIVATE ServerSocket SS = null; 
 
  Client socket PRIVATE SOCKET socket = NULL; 
    public void Start () {try {//start server SS = new ServerSocket (8888); 
      catch (Bindexception e) {System.out.println ("port is already in use"); 
    Close Program System.exit (0); 
    catch (Exception e) {e.printstacktrace (); 
      try {Isstart = true; 
        while (Isstart) {//start listening socket = Ss.accept (); 
        SYSTEM.OUT.PRINTLN ("One client Connect"); Start Client Thread ClIent client = new Client (socket); 
      New Thread (client). Start (); 
    } catch (Exception e) {e.printstacktrace (); 
      Finally {//close service try {ss.close (); 
      catch (IOException e) {e.printstacktrace (); 
    }}/** * Client thread * * * @author tuzongxun123 */class client implements Runnable { 
    Client socket PRIVATE SOCKET socket = NULL; 
    Client input stream private DataInputStream datainputstream = null; 
 
    Private Boolean isconnect = false; 
      Public Client (socket socket) {this.socket = socket; 
        try {isconnect = true; 
      Gets the client input stream datainputstream = new DataInputStream (Socket.getinputstream ()); 
      catch (IOException e) {e.printstacktrace (); 
      @Override public void Run () {isconnect = true; try {while (isconnect) {//Read the client-passed data String message = DatAinputstream.readutf (); 
        SYSTEM.OUT.PRINTLN ("Client said:" + message); 
      The catch (Eofexception e) {System.out.println ("client closed!"); 
      catch (SocketException e) {System.out.println ("Client is Closed!!!!"); 
      catch (Exception e) {e.printstacktrace (); 
          Finally {//close related resources try {datainputstream.close (); 
        Socket.close (); 
        catch (IOException e) {e.printstacktrace (); 
 } 
      } 
    } 
 
  } 
 
}

The above mainly introduces the use of threads to enable the server to achieve the ability to receive multiple client requests, where the client will need to receive multiple client messages can also be forwarded to each connected client, and the client should be able to display in the content display area, so as to achieve a simple online group chat.

In the implementation of client forwarding, is simply to increase the output stream, and before the client has only been sent, here also need to change the client to achieve the purpose of circular receive server messages, so also need to implement multithreading.

In the implementation of this function, the occasional thought of the random generation of verification code function, so also brainwave randomly to generate a name for each client, so that when the output looks more like a group chat, not only the message output, but also to see who.

After implementing these features, you can basically chat online with a few people at the same time, because there is a main method in the code, so you can put both the server and the client into an executable jar package, and refer to my other blog post: Use Eclipse to create a Java program executable jar package

Then double-click the appropriate jar file on the desktop to start the server and the client, and no longer need to rely on eclipse to run.

The modified client code is as follows:

Package chat.chat; 
Import Java.awt.BorderLayout; 
Import Java.awt.Frame; 
Import Java.awt.TextArea; 
Import Java.awt.TextField; 
Import java.awt.event.ActionEvent; 
Import Java.awt.event.ActionListener; 
Import Java.awt.event.WindowAdapter; 
Import java.awt.event.WindowEvent; 
Import Java.io.DataInputStream; 
Import Java.io.DataOutputStream; 
Import java.io.IOException; 
Import Java.net.Socket; 
Import java.net.UnknownHostException; 
 
Import Java.util.Random; /** * Online chat client steps: * 1, Generate graphics Window interface profile * 2, add a shutdown event for Contour * 3, include input area and content display area in contour *4, add carriage return event for input area * 5, establish service-side connection and send data * * @author tuzongxun123 * */public class ChatClient extends Frame {/** */private static final long SE 
  Rialversionuid = 1L; 
  User input area private TextField tftxt = new TextField (); 
  Content display area private TextArea Tarea = new TextArea (); 
  Private socket socket = NULL; 
  Data output stream private dataoutputstream dataoutputstream = null; Data input stream Private DataInputStream datainputstrEAM = null; 
  Private Boolean isconnect = false; 
  Thread treceive = new Thread (new Receivethread ()); 
 
  String name = ""; 
    public static void Main (string[] args) {chatclient chatclient = new ChatClient (); 
    Chatclient.createname (); 
 
  Chatclient.launcframe ();  /** * Create a simple graphical window * * @author: Tuzongxun * @Title: Launcframe * @param * @return void * 
    @date May, 2016 9:57:00 AM * @throws/public void Launcframe () {setlocation (300, 200); 
    This.setsize (200, 400); 
    Add (Tftxt, Borderlayout.south); 
    Add (Tarea, Borderlayout.north); 
    The optimal size pack () of the frame is determined according to the layout inside the window and the preferedsize of the component. The Shutdown Event This.addwindowlistener (new Windowadapter () {@Override public void windowclosing (Win 
        Dowevent e) {system.exit (0); 
      DisConnect (); 
    } 
    }); 
    Tftxt.addactionlistener (New Tflister ()); 
    The Set window is visible setvisible (true); 
    Connect (); That initiates the acceptance of the message.Thread Treceive.start ();  /** * Connect Server * * @author: Tuzongxun * @Title: Connect * @param * @return void * @date May 2016 9:56:49 AM * @throws/public void Connect () {try {//new server connection socket = new sock 
      ET ("127.0.0.1", 8888); 
      Gets the client output stream dataoutputstream = new DataOutputStream (Socket.getoutputstream ()); 
      DataInputStream = new DataInputStream (Socket.getinputstream ()); 
      System.out.println ("connected to the service end"); 
    Isconnect = true; 
    catch (Unknownhostexception e) {e.printstacktrace (); 
    catch (IOException e) {e.printstacktrace (); }//Generate random client name public void Createname () {string[] str1 = {"A", "B", "C", "D", "E", "F", "G", "H", "I" , "J", "K", "L", "M", "N", "O", "P", "Q", "R", "s", "T", "U", "V", "w", "X", "Y", "Z", "1", "2", "3", "4 "," 5 "," 6 "," 7 "," 8 "," 9 "," 0 "," A "," B "," C "," D "," E "," F "," G "," H "," I "," J "," K ""," L "," M "," N "," O "," P "," Q "," R "," S "," T "," U "," V "," W "," X "," Y "," Z "}; 
 
    Random ran = new Random (); 
      for (int i = 0; i < 6; i++) {//Long num = Math.Round (Math.random () * (str1.length-0) + 0); 
      int n = (int) num; 
      int n = ran.nextint (str1.length); 
        if (n < str1.length) {String str = str1[n]; 
        Name = name + str; 
      SYSTEM.OUT.PRINTLN (name); 
        else {i--; 
      Continue 
  } this.settitle (name); /** * Close Client Resource * * @author: Tuzongxun * @Title: DisConnect * @param * @return void * @dat 
      E May, 2016 9:57:46 AM * @throws/public void DisConnect () {try {isconnect = false; 
    Stop thread treceive.join (); 
    catch (Interruptedexception e) {e.printstacktrace (); 
        Finally {try {if (DataOutputStream!= null) {dataoutputstream.close (); } if(Socket!= NULL) 
          {Socket.close (); 
        socket = NULL; 
      } catch (IOException e) {e.printstacktrace (); 
   /** * Send Message to Server * * @author: Tuzongxun * @Title: SendMessage * @param @param text * @return void * @date May, 2016 9:57:56 AM * @throws/private void SendMessage (String text) {T 
      ry {DATAOUTPUTSTREAM.WRITEUTF (name + ":" + text); 
    Dataoutputstream.flush (); 
    catch (IOException E1) {e1.printstacktrace (); }/** * Graphics window Input Area Monitor carriage return event * * @author tuzongxun123 */Private class Tflister implements Ac Tionlistener {@Override public void actionperformed (ActionEvent e) {String text = Tftxt.gettext (). Tri 
      M (); 
      Empty the input area information Tftxt.settext (""); 
    Send data to server after carriage SendMessage (text); } Private class Receivethread implements Runnable {@Override public void Run () {try {while (isconnect) {String message = Datainputstream.readutf (); 
          SYSTEM.OUT.PRINTLN (message); 
          String txt = tarea.gettext (); if (txt!= null &&! "". 
          Equals (Txt.trim ())) {message = Tarea.gettext () + "\ n" + message; 
        } tarea.settext (message); 
      } catch (IOException e) {e.printstacktrace (); 

 } 
    } 
 
  } 
}

The

Modified server-side code is as follows:

Package chat.chat; 
Import Java.io.DataInputStream; 
Import Java.io.DataOutputStream; 
Import java.io.EOFException; 
Import java.io.IOException; 
Import java.net.BindException; 
Import Java.net.ServerSocket; 
Import Java.net.Socket; 
Import java.net.SocketException; 
Import java.util.ArrayList; 
 
Import java.util.List; 
 /** * Java uses socket and AWT components as well as multithreading simple implementation of online chat function server: * Implement server to forward received client information to all connected clients, and have the client read this information and display in the content display area. * * * @author tuzongxun123 * */public class Chatserver {public static void main (string[] args) {new Chat 
  Server (). Start (); 
  }//Whether the server is successfully started private Boolean isstart = false; 
  Server Socket PRIVATE ServerSocket SS = null; 
  Client socket PRIVATE SOCKET socket = NULL; 
 
  Save the Client collection list<client> clients = new arraylist<client> (); 
    public void Start () {try {//start server SS = new ServerSocket (8888); 
      catch (Bindexception e) {System.out.println ("port is already in use"); Close Program System.exIt (0); 
    catch (Exception e) {e.printstacktrace (); 
      try {Isstart = true; 
        while (Isstart) {//start listening socket = Ss.accept (); 
        SYSTEM.OUT.PRINTLN ("One client Connect"); 
 
        Start client-side Thread clients = new client (socket); 
        New Thread (client). Start (); 
      Clients.add (client); 
    } catch (Exception e) {e.printstacktrace (); 
      Finally {//close service try {ss.close (); 
      catch (IOException e) {e.printstacktrace (); }}/** * Client thread * * * @author tuzongxun123 */Private class Client implements Runn 
    Able {//client socket private SOCKET socket = NULL; 
    Client input stream private DataInputStream datainputstream = null; 
    Client output stream private dataoutputstream dataoutputstream = null; 
 
    Private Boolean isconnect = false; 
     Public Client (socket socket) {this.socket = socket; try {isconnect = true; 
        Gets the client input stream datainputstream = new DataInputStream (Socket.getinputstream ()); 
      Gets the client output stream dataoutputstream = new DataOutputStream (Socket.getoutputstream ()); 
      catch (IOException e) {e.printstacktrace (); /** * Mass (forward) data to client * * @author: Tuzongxun * @Title: sendmessagetoclients * @p Aram @param message * @return void * @date May, 2016 11:28:10 AM * @throws/public void 
      Sendmessagetoclients (String message) {try {dataoutputstream.writeutf (message); 
      catch (SocketException e) {} catch (IOException e) {e.printstacktrace (); 
      @Override public void Run () {isconnect = true; 
      Client c = null; 
          try {while (isconnect) {//Read the client-passed data String message = Datainputstream.readutf (); System.oUT.PRINTLN ("Client said:" + message); 
 
            for (int i = 0; i < clients.size (); i++) {c = Clients.get (i); 
          c.sendmessagetoclients (message); 
      The catch (Eofexception e) {System.out.println ("client closed!"); 
        catch (SocketException e) {if (c!= null) {Clients.remove (c); 
      } System.out.println ("Client is Closed!!!!"); 
      catch (Exception e) {e.printstacktrace (); Finally {//close related resource try {if (DataInputStream!= null) {Datainputstream.close 
          (); 
            } if (socket!= null) {socket.close (); 
          socket = NULL; 
        } catch (IOException e) {e.printstacktrace (); 
 } 
      } 
    } 
  } 
 
}

First introduced to you here, and then if there are new content for everyone to update.

Online chat about the realization of the function of large, we can also refer to a few articles to learn:

Java realizes a simple tcpsocket chat room function sharing

The above is the entire content of this article, I hope to help you learn, but also hope that you can continue to pay attention to the cloud-dwelling community more wonderful content.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.