Java multithread Implementation chat client and server _java

Source: Internet
Author: User
Tags flush gettext readline thread class server port

This example for you to share the Java Chat Room code, for your reference, the specific contents are as follows

Mainly involved in knowledge

· Java GUI program writing, including event monitoring mechanism.
· Java network communication Programming, the use of serversocket,socket classes.
· Multi-Threading Programming in Java, Thread class, the use of runnable interfaces.

Source

Client

Package Project1; 
Import java.awt.*; 
Import java.awt.event.*; 
Import java.io.*; 
 
Import java.net.*; 
 
Import javax.swing.*; 
 public class Client {private JFrame clientframe; 
 Private JLabel Iplabel; 
 Private JLabel Portlabel; 
 Private JLabel Saylabel; 
 Private JLabel Nicknamelabel; 
 Private JTextField Iptext; 
 Private JTextField Porttext; 
 Private JTextField Nicknametext; 
 Private JTextField Saytext; 
 Private JButton Connectbutton; 
 Private JButton Nicknamebutton; 
 Private JButton Saybutton; 
 Private JPanel Jpanelnorth; 
 Private JPanel JPanelSouth0; 
 Private JPanel jPanelSouth1; 
 Private JPanel jPanelSouth2; 
 Private JTextArea Clienttextarea; 
 Private JScrollPane scroller; 
 Private BufferedReader reader; 
 Private PrintWriter writer; 
 
 Private String nickname; 
  public static void Main (String args[]) {Client aclient = new Client (); 
 Aclient.startup (); 
 
  }//Initialize Component public client () {nickname = "client"; 
  Clientframe = new JFrame (); JpanElnorth = new JPanel (); 
  Iplabel = new JLabel ("Server IP", jlabel.left); 
  Iptext = new JTextField (10); 
  Portlabel = new JLabel ("Server Port", jlabel.left); 
  Porttext = new JTextField (10); 
  Connectbutton = new JButton ("Connection"); 
  Clienttextarea = new JTextArea (); 
  Scroller = new JScrollPane (Clienttextarea); 
  JPanelSouth0 = new JPanel (); 
  JPanelSouth1 = new JPanel (); 
  JPanelSouth2 = new JPanel (); 
  Nicknamelabel = new JLabel ("nickname", Jlabel.left); 
  Nicknametext = new JTextField (nickname, 30); 
  Nicknamebutton = new JButton ("Confirm"); 
  Saylabel = new JLabel ("message", Jlabel.left); 
  Saytext = new JTextField (30); 
 Saybutton = new JButton ("Confirm"); 
  ///Build GUI private void Buildgui () {//Window settings Clientframe.settitle ("Client"); 
  Clientframe.setdefaultcloseoperation (Jframe.exit_on_close); 
 
  Clientframe.setsize (550, 550); 
  North of the Component Jpanelnorth.add (Iplabel); 
  Jpanelnorth.add (Iptext); 
  Jpanelnorth.add (Portlabel); 
  Jpanelnorth.add (Porttext); Jpanelnorth.add (connectbutton); 
 
  Clientframe.getcontentpane (). Add (Borderlayout.north, Jpanelnorth); 
  The middle component clienttextarea.setfocusable (false); 
  Scroller.setverticalscrollbarpolicy (scrollpaneconstants.vertical_scrollbar_always); 
  Scroller.sethorizontalscrollbarpolicy (Scrollpaneconstants.horizontal_scrollbar_never); 
 
  Clientframe.getcontentpane (). Add (Borderlayout.center, scroller); 
  The Southern Component Jpanelsouth1.add (Nicknamelabel); 
  Jpanelsouth1.add (Nicknametext); 
  Jpanelsouth1.add (Nicknamebutton); 
  Jpanelsouth2.add (Saylabel); 
  Jpanelsouth2.add (Saytext); 
  Jpanelsouth2.add (Saybutton); 
  Jpanelsouth0.setlayout (New BoxLayout (JPanelSouth0, Boxlayout.y_axis)); 
  Jpanelsouth0.add (JPANELSOUTH1); 
  Jpanelsouth0.add (JPANELSOUTH2); 
 
  Clientframe.getcontentpane (). Add (Borderlayout.south, JPanelSouth0); 
 The Set window is visible clientframe.setvisible (true); 
 
  //client runs public void StartUp () {Buildgui (); The thread that received the server message Runnable Incomingreader = new Runnable () {@Override publicvoid Run () {String message; 
     try {while (message = Reader.readline ())!= null) {clienttextarea.append (message + "\ n"); 
    } catch (Exception ex) {ex.printstacktrace (); 
 
  } 
   } 
  }; Monitor the Connect button to implement the server's connection Connectbutton.addactionlistener (new ActionListener () {@Override public void Actionperf 
    Ormed (ActionEvent e) {String Aserverip = Iptext.gettext (); 
 
    String Aserverport = Porttext.gettext (); if (Aserverip.equals ("") | | Aserverport.equals ("")) {Joptionpane.showmessagedialog (clientframe, "Please enter the full IP and port!") 
    "); else {try {@SuppressWarnings ("resource") socket Clientsocket = new socket (Aserverip, Integer.parse 
      Int (Aserverport)); 
      InputStreamReader StreamReader = new InputStreamReader (Clientsocket.getinputstream ()); 
      reader = new BufferedReader (StreamReader); 
 
      writer = new PrintWriter (Clientsocket.getoutputstream ()); 
Clienttextarea.append ("server is connected ... \ n"); 
      Thread readerthread = new Thread (incomingreader); 
     Readerthread.start (); The catch (Exception ex) {Joptionpane.showmessagedialog (clientframe) is not connected to the server!\n verify that the IP and port inputs are correct. 
     "); 
 
  } 
    } 
   } 
  }); Monitor nickname, set nickname ActionListener Nicknamelistener = new ActionListener () {@Override public void Actionperform 
    Ed (ActionEvent e) {String atext = Nicknametext.gettext (); 
    if (!atext.equals ("")) {nickname = Atext; 
  } 
   } 
  }; 
  Nicknamebutton.addactionlistener (Nicknamelistener); 
  Nicknametext.addactionlistener (Nicknamelistener); 
 
   Nicknametext.addfocuslistener (New Focuslistener () {@Override public void focusgained (FocusEvent e) {} 
    @Override public void Focuslost (FocusEvent e) {String atext = Nicknametext.gettext (); 
    if (!atext.equals ("")) {nickname = Atext; 
 
  } 
   } 
  }); Send message to server ActionListener Saylistener = new ActionListener () {@Override public void actIonperformed (ActionEvent e) {String atext = Saytext.gettext (); if (Atext.equals (")) {Joptionpane.showmessagedialog (clientframe," content cannot be empty!) 
    "); 
      else {try {writer.println (nickname + ":" + atext); 
     Writer.flush (); 
     catch (Exception ex) {ex.printstacktrace (); 
    } saytext.settext (""); 
  } 
   } 
  }; 
  Saybutton.addactionlistener (Saylistener); 
 
 Saytext.addactionlistener (Saylistener); 

 } 
 
}

Server

Package Project1; 
Import java.awt.*; 
Import java.awt.event.*; 
Import java.io.*; 
Import java.net.*; 
Import java.util.ArrayList; 
Import Java.util.Iterator; 
 
Import javax.swing.*; 
 public class Server {private JFrame serverframe; 
 Private JLabel Portlabel; 
 Private JLabel Saylabel; 
 Private JLabel Nicknamelabel; 
 Private JTextField Porttext; 
 Private JTextField Saytext; 
 Private JTextField Nicknametext; 
 Private JButton Startbutton; 
 Private JButton Saybutton; 
 Private JButton Nicknamebutton; 
 Private JPanel Jpanelnorth; 
 Private JPanel JPanelSouth0; 
 Private JPanel jPanelSouth1; 
 Private JPanel jPanelSouth2; 
 Private JScrollPane scroller; 
 Private JTextArea Servertextarea; 
 Private arraylist<printwriter> Clientoutputstreams; 
 
 Private String nickname; 
  public static void Main (string[] args) {Server aserver = new server (); 
 Aserver.startup (); 
 
  }//Initialize Component Public server () {nickname = "Server"; 
  Serverframe = new JFrame (); Jpanelnorth = new JPanel (); 
  Portlabel = new JLabel ("Port", jlabel.left); 
  Porttext = new JTextField (30); 
  Startbutton = new JButton ("Start"); 
  Servertextarea = new JTextArea (); 
  Scroller = new JScrollPane (Servertextarea); 
  Nicknamelabel = new JLabel ("nickname", Jlabel.left); 
  Nicknametext = new JTextField (nickname, 30); 
  Nicknamebutton = new JButton ("Confirm"); 
  JPanelSouth0 = new JPanel (); 
  JPanelSouth1 = new JPanel (); 
  JPanelSouth2 = new JPanel (); 
  Saylabel = new JLabel ("message", Jlabel.left); 
  Saytext = new JTextField (30); 
 Saybutton = new JButton ("Confirm"); 
  ///Build GUI private void Buildgui () {//Window settings serverframe.settitle ("Server"); 
  Serverframe.setdefaultcloseoperation (Jframe.exit_on_close); 
 
  Serverframe.setsize (550, 550); 
  North of the Component Jpanelnorth.add (Portlabel); 
  Jpanelnorth.add (Porttext); 
  Jpanelnorth.add (Startbutton); 
 
  Serverframe.getcontentpane (). Add (Borderlayout.north, Jpanelnorth); 
  The middle component servertextarea.setfocusable (false); Scroller.setvertIcalscrollbarpolicy (scrollpaneconstants.vertical_scrollbar_always); 
  Scroller.sethorizontalscrollbarpolicy (Scrollpaneconstants.horizontal_scrollbar_never); 
 
  Serverframe.getcontentpane (). Add (Borderlayout.center, scroller); 
  The Southern Component Jpanelsouth1.add (Nicknamelabel); 
  Jpanelsouth1.add (Nicknametext); 
  Jpanelsouth1.add (Nicknamebutton); 
  Jpanelsouth2.add (Saylabel); 
  Jpanelsouth2.add (Saytext); 
  Jpanelsouth2.add (Saybutton); 
  Jpanelsouth0.setlayout (New BoxLayout (JPanelSouth0, Boxlayout.y_axis)); 
  Jpanelsouth0.add (JPANELSOUTH1); 
  Jpanelsouth0.add (JPANELSOUTH2); 
 
  Serverframe.getcontentpane (). Add (Borderlayout.south, JPanelSouth0); 
 The Set window is visible serverframe.setvisible (true); 
 
  }//server running public void StartUp () {Buildgui (); Monitor the Start button to establish the port ActionListener Startlistener = new ActionListener () {@Override public void actionperformed (A 
    Ctionevent e) {clientoutputstreams = new arraylist<printwriter> (); String Aport = Porttext.getText (); if (Aport.equals (")) {Joptionpane.showmessagedialog (serverframe, please enter the correct port number!) 
    "); ' Else {try {//thread waiting for client to connect Runnable serverrunnable = new Runnable () {@Override Publ 
        IC void Run () {ServerSocket serversocket; 
         try {serversocket = new ServerSocket (Integer.parseint (Aport)); 
         Servertextarea.append ("Waiting for client to connect ... \ n"); 
          while (true) {Socket clientsocket = serversocket.accept (); 
 
          Servertextarea.append ("Client connected ... \ n"); 
          PrintWriter writer = new PrintWriter (Clientsocket.getoutputstream ()); 
 
          Clientoutputstreams.add (writer); 
          Thread t = new Thread (new ClientHandler (Clientsocket)); 
         T.start (); catch (NumberFormatException | 
        IOException e) {e.printstacktrace (); 
      } 
       } 
      }; 
      Thread serverthread = new Thread (serverrunnable); 
     Serverthread.start (); catch (ExCeption ex) {ex.printstacktrace (); 
  } 
    } 
   } 
  }; 
  Startbutton.addactionlistener (Startlistener); 
 
  Porttext.addactionlistener (Startlistener); Monitor nickname, set nickname ActionListener Nicknamelistener = new ActionListener () {@Override public void Actionperform 
    Ed (ActionEvent e) {String atext = Nicknametext.gettext (); 
    if (!atext.equals ("")) {nickname = Atext; 
  } 
   } 
  }; 
  Nicknamebutton.addactionlistener (Nicknamelistener); 
  Nicknametext.addactionlistener (Nicknamelistener); 
 
   Nicknametext.addfocuslistener (New Focuslistener () {@Override public void focusgained (FocusEvent e) {} 
    @Override public void Focuslost (FocusEvent e) {String atext = Nicknametext.gettext (); 
    if (!atext.equals ("")) {nickname = Atext; 
 
  } 
   } 
  }); Listen for say button, send message ActionListener Saylistener = new ActionListener () {@Override public void actionperformed (actio Nevent e) {String atext = saytext.gEttext (); 
     if (!atext.equals ("")) {atext = nickname + ":" + atext; 
     Sendtoeveryclient (Atext); 
     Servertextarea.append (atext + "\ n"); 
    Saytext.settext (""); else {Joptionpane.showmessagedialog (serverframe, "content cannot be empty!) 
    "); 
  } 
   } 
  }; 
  Saybutton.addactionlistener (Saylistener); 
 Saytext.addactionlistener (Saylistener); 
  }//Multi-client thread public class ClientHandler implements Runnable {BufferedReader breader; 
 
  Socket Asocket; 
    Public ClientHandler (Socket clientsocket) {try {asocket = Clientsocket; 
    InputStreamReader Isreader = new InputStreamReader (Asocket.getinputstream ()); 
   Breader = new BufferedReader (Isreader); 
   catch (Exception ex) {ex.printstacktrace (); 
   @Override public void Run () {String message; 
     try {while (message = Breader.readline ())!= null) {sendtoeveryclient (message); 
    Servertextarea.append (message + "\ n"); 
 } catch (Exception ex) {   Ex.printstacktrace (); }}//Send message to all clients private void sendtoeveryclient (String message) {iterator<printwriter> it = CLI 
  Entoutputstreams.iterator (); 
    while (It.hasnext ()) {try {printwriter writer = (PrintWriter) it.next (); 
    WRITER.PRINTLN (message); 
   Writer.flush (); 
   catch (Exception ex) {ex.printstacktrace (); 
 } 
  } 
 } 
 
}

GUI Run screenshot:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.