Implementation of a simple online chat function based on Java socket (i) _java

Source: Internet
Author: User
Tags socket

Recently done a project, which has an online web exchange needs, haven't written code for a long time, hands are unfamiliar, so first write demo practice practicing, share to cloud Habitat community platform, so as to make a record, convenient for themselves and everyone to use.

First of all, I would like to say that the implementation of steps in such a few strides:

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.

The code to implement the functionality is as follows:

Client:

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 (Windo 
        Wevent e) {system.exit (0); 
      DisConnect (); 
    } 
    }); 
    Tftxt.addactionlistener (New Tflister ()); 
    SetVisible (TRUE); 
  Connect (); /** * Connection Server * * @author: Tuzongxun * @Title: Connect * @param * @return void * @date May 1 8, 2016 9:56:49 AM * @throws/public void Connect () {try {//new server connection socket = new socket 
      ("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 * @retur 
      n 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 ACTI  
Onlistener {@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 Mai 
    N (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 ();  } 
    } 
  } 
}

The above is a small series of Java socket to introduce the implementation of a simple online chat function (a) of the relevant knowledge, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.