Java implementation of multiplayer online chat room (socket and serversocket application) __java

Source: Internet
Author: User
Tags event listener gettext readline thread class

First place Effect chart:



Landing:


/** ChatClient class */import Java.awt.BorderLayout in the vicinity of the 109 lines of this class;
Import Java.awt.FlowLayout;
Import Java.awt.Toolkit;
Import Java.io.File;
Import java.io.IOException;
Import Java.net.Socket;
Import java.net.UnknownHostException;
Import Java.awt.event.ActionListener;
Import java.awt.event.ActionEvent;
Import Javax.swing.BorderFactory;
Import Javax.swing.Icon;
Import Javax.swing.ImageIcon;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
Import Javax.swing.JOptionPane;
Import Javax.swing.JPanel;
Import Javax.swing.JPasswordField;
Import Javax.swing.JTextField;
Import Javax.swing.border.Border;
Import Javax.swing.border.EtchedBorder;


Import Javax.swing.border.TitledBorder;
    public class Clientlogin extends JFrame {private JTextField nametext;
    Private JPasswordField Passwordtetx;
   
    Private Object Bpanel;       Public Clientlogin () {this.init ();
        Init method initializes this.setdefaultcloseoperation (Exit_on_close); ThiS.setvisible (TRUE);
        public void init () {this.settitle ("Stay-meng Chat room login");     This.setsize (330,230);
        Borrow Mature and beautiful dimensions int y = (int) toolkit.getdefaulttoolkit (). Getscreensize (). GetHeight ();
                int x = (int) toolkit.getdefaulttoolkit (). Getscreensize (). GetWidth ();
                 /** above method is hard to remember without the help of Eclipse, ni.
      * */This.setlocation ((X-this.getwidth ())/2, (Y-this.getheight ())/2);     This.setresizable (FALSE);
      Do not allow users to change their size icon icon = new ImageIcon ("D:" +file.separator+ "login.jpg");   JLabel label = new JLabel (icon);
     
      Set the landing interface on the border This.add (Label,borderlayout.north);
      JPanel Mainpanel = new JPanel ();
      Border Border = Borderfactory.createetchedborder (etchedborder.lowered);
      Mainpanel.setborder (Borderfactory.createtitledborder (Border, "Input login Information", titledborder.center,titledborder.top));     This.add (Mainpanel,borderlayout.center); Add the main panel to the frame Mainpanel.setlayoUT (NULL);
      JLabel Namelabel = new JLabel ("Please enter a nickname");
      Namelabel.setbounds (30,30,80,22);
      Mainpanel.add (Namelabel);
      Nametext = new JTextField ();
      Nametext.setbounds (115,30,120,22);
      Mainpanel.add (Nametext);
      JLabel Passwordlabel = new JLabel ("Please enter password");
      Passwordlabel.setbounds (30,60,80,22);
      Mainpanel.add (Passwordlabel);
      Passwordtetx = new JPasswordField ();
      Passwordtetx.setbounds (115,60,120,22);
     
      Mainpanel.add (PASSWORDTETX);
     Next button position emission JPanel Bpanel = new JPanel ();
     Bpanel.setlayout (New FlowLayout (flowlayout.right));
     This.add (Bpanel,borderlayout.south);
     JButton reset = new JButton ("reset");
             Reset.addactionlistener (new ActionListener () {//For reset button to add event listener public void actionperformed (ActionEvent e) {
             Nametext.settext ("");
         Passwordtetx.settext ("");
     }
         });
     
     Bpanel.add (reset);
     
 /** below Start implementation Submit Button * * * *    JButton Submit = new JButton ("Landing");  Submit.addactionlistener (This) (new loginaction);
Because landing relatively complex, again for landing write a class bpanel.add (submit);
    Under/** Start Write Login class * */Class Loginaction implements ActionListener {private JFrame self;
    Public loginaction (JFrame self) {this.self = self; The public void actionperformed (ActionEvent e) {//system.out.println ("username is:" +nametext.gettext () + "password is:" +ne
        W String (Passwordtext.getpassword ()));
            try {//Start connecting to the server socket socket = new Socket ("127.0.0.1", 8888);
            New ChatClient (Socket,nametext.gettext ());
        Call Dispose method to close the landing box Self.dispose ();
            }catch (unknownhostexception E1) {e1.printstacktrace ();
        Joptionpane.showconfirmdialog (self, "cannot find the specified server!~", "Connection Failed", joptionpane.ok_option,joptionpane.error_message);
            }catch (IOException E1) {e1.printstacktrace (); Joptionpane.showconfirmdialog (SElf, "Connection server error, please try again."
        "," Connection Failed ", joptionpane.ok_option,joptionpane.error_message);
    }} public static void Main (String args[]) {new Clientlogin ();
 }
}



Client:

Import Java.awt.BorderLayout;
Import Java.awt.FlowLayout;
Import Java.awt.Toolkit;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.Socket;
Import Java.util.Date;
Import Java.text.SimpleDateFormat;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
Import Javax.swing.JPanel;
Import Javax.swing.JScrollPane;
Import Javax.swing.JSplitPane;


Import Javax.swing.JTextArea;                  public class ChatClient extends JFrame {private socket socket;        Responsible for and server communication private JTextArea Sendarea;   Message editing area private JTextArea Contentarea;                   Group Chat message Display box private String name;
        The current user name is public chatclient (socket socket,string name) {this.socket = socket;
        THIS.name = name;       This.init (); Initializing a chat client
        This.setdefaultcloseoperation (Exit_on_close);
       
        This.setvisible (TRUE);  /* Next start a separate thread to read data specifically from the server * */clientthread thread = new Clientthread (Socket,contentarea)
        ;
    Thread.Start ();
        public void init () {this.settitle ("My chat room");
        This.setsize (300,400);
        int x = (int) toolkit.getdefaulttoolkit (). Getscreensize (). GetWidth ();
       
        int y = (int) toolkit.getdefaulttoolkit (). Getscreensize (). GetHeight ();
        This.setlocation ((X-this.getwidth ())/2, (Y-this.getheight ())/2);      This.setresizable (FALSE);
        Do not allow user to change size Contentarea = new JTextArea ();  Contentarea.setlinewrap (TRUE); Line-Wrapping method JScrollPane Logpanel = new JScrollPane (Contentarea, Jscrollpane.vertical_scrollbar_as_need
       
        ED, Jscrollpane.horizontal_scrollbar_never);
        Sendarea = new JTextArea ();    Sendarea.setlinewrap (TRUE); //Controls the maximum length of each line display not exceeding the interface length JScrollPane Sendpanel = new JScrollPane (Sendarea, Jscrollpane.vertical_scrollba
       
        r_as_needed, Jscrollpane.horizontal_scrollbar_never);
        Create a divider pane jsplitpane Splitpane = new JSplitPane (Jsplitpane.vertical_split,logpanel,sendpanel);
        Splitpane.setdividerlocation (250);
       
        This.add (Splitpane,borderlayout.center);
        Button panel JPanel bpanel = new JPanel ();
        Bpanel.setlayout (New FlowLayout (flowlayout.right));
       
        This.add (Bpanel,borderlayout.south);
        JLabel Namelabel = new JLabel ("nickname:" +this.name+ ");
       
        Bpanel.add (Namelabel);
        JButton CloseButton = new JButton ("close");
               
            Closebutton.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {
        }
        });
       
        Bpanel.add (CloseButton); JButton Sendbutton = new JButton ("Send"); Sendbutton.addactionlistener (new ActionListener () {//@Override public void actionperformed (Action
                Event arg0) {//TODO auto-generated method stub String str = Sendarea.gettext ();
                SimpleDateFormat formater = new SimpleDateFormat ("HH:mm:ss");
                String time = Formater.format (new Date ());
                String sendstr = name+ "+time+" said: "+STR;"
                PrintWriter out = null;
                    try {out = new PrintWriter (New OutputStreamWriter (Socket.getoutputstream ()));
                    Out.println (SENDSTR);
                Out.flush ();
                }catch (Exception E1) {e1.printstacktrace ();
            } sendarea.settext ("");
       
        }
        });   
    Bpanel.add (Sendbutton);
    }///client-server-side communication thread class Clientthread extends thread {private socket socket; PrivAte JTextArea Contentarea;
        Public Clientthread (socket socket, JTextArea contearea) {this.socket = socket;
    This.contentarea = Contearea;
        public void Run () {BufferedReader br = null;
            try {br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
                    String str = NULL;
                        while (str = Br.readline ())!= null) {System.out.println (str);
                        Contentarea.append (str);
                    Contentarea.append ("\ n");
        } catch (IOException e) {e.printstacktrace ();
                finally {if (br!= null) {try {br.close ();
            }catch (IOException e) {e.printstacktrace (); }
        }
    }
}}

Server side:

Import java.util.List;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;


Import java.util.ArrayList;    public class Chatserver {private list<socket> sockets = new arraylist<socket> ();
        The application of the class set is public Chatserver () throws IOException {ServerSocket ss = new ServerSocket (8888);
       
        SYSTEM.OUT.PRINTLN ("Server is listening on port 8888");
            while (true) {Socket socket = ss.accept ();
            Sockets.add (socket);
            String IP = socket.getinetaddress (). gethostaddress (); SYSTEM.OUT.PRINTLN ("New user entered.")
            IP is "+ip";
            Thread thread = new Thread (new Serverrunner (Sockets,socket));
        Thread.Start ();
        } public static void Main (String args[]) {try {new chatserver (); catch (Exception e) {E.priNtstacktrace ();
    }} class Serverrunner implements Runnable {private list<socket> sockets;   Private Socket Currentsocket;  Current Socket public Serverrunner (list<socket> sockets,socket currentsocket) {this.sockets = sockets
        ;
    This.currentsocket = Currentsocket;
        public void Run () {String IP = currentsocket.getinetaddress (). gethostaddress ();
        BufferedReader br = null;
            try {br = new BufferedReader (New InputStreamReader (Currentsocket.getinputstream ()));
            String str = NULL;
                while (str = Br.readline ())!= null) {SYSTEM.OUT.PRINTLN (ip+ "said" +str); Write information to all clients for (Socket temp:sockets) {printwriter pw = new Print
                    Writer (New OutputStreamWriter (Temp.getoutputstream ()));
                    Pw.println (str);
                Pw.flush ();
          }  }}catch (IOException e) {e.printstacktrace ();
 }
    }
}



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.