Java using socket network programming to realize multi-person chat room __ algorithm

Source: Internet
Author: User
Tags gettext sendmsg

The socket (socket) programming can realize the communication between the server and the client, the following through the socket programming combined with multithreading to achieve a multiplayer chat room.
Program Show:

Interface Class

1. Client Interface Clientview.java

public class Clientview extends JFrame implements ActionListener, KeyListener, Runnable {private JTextArea textArea;
    Private JTextField TextField, tfname;
    Private JButton btnsend, Btnid;
    Private JLabel label;
    Private JPanel jp1, JP2;
    public Boolean isconnect = false;
    Private socket socket = NULL;
    Private DataInputStream InputStream = null;
    Private DataOutputStream outputstream = null;
    Private JScrollPane ScrollPane;

    private static Clientview view;
    Public JTextArea Gettextarea () {return textArea;
    Public DataInputStream getInputStream () {return inputstream;
    Public DataOutputStream Getoutputstream () {return outputstream;
        public static void Main (string[] args) {view = new Clientview ();
        ServiceView.clientViews.add (view);
        Thread thread = new thread (view);
    Thread.Start ();
        Public Clientview () {Initview (); try {SocKet = new Socket ("localhost", 9090);//connect local server} catch (Unknownhostexception e) {e.printstacktrace ();
        catch (IOException e) {e.printstacktrace ();
        } private void Initview () {TextArea = new JTextArea (20, 20);
        Textarea.seteditable (FALSE);
        ScrollPane = new JScrollPane (TextArea);
        TextField = new JTextField (15);
        Textfield.addkeylistener (this);
        Btnsend = new JButton ("send");
        Btnsend.addactionlistener (this);
        label = new JLabel ("nickname:");
        Tfname = new JTextField (8);
        JP1 = new JPanel ();
        JP2 = new JPanel ();
        Jp1.add (label);
        Jp1.add (tfname);
        Tfname.settext ("User 0");
        Jp1.setlayout (New FlowLayout (Flowlayout.center));
        Jp2.add (TextField);
        Jp2.add (Btnsend);

        Jp2.setlayout (New FlowLayout (Flowlayout.center));
        Add (Jp1, Borderlayout.north);
        Add (ScrollPane, borderlayout.center); Add (JP2, Borderlayout.south);
        Settitle ("chat room");
        SetSize (500, 500);
        setlocation (450, 150);
        SetVisible (TRUE);
        Setdefaultcloseoperation (Exit_on_close); Addwindowlistener (New Windowadapter () {//window closed after disconnecting @Override public void windowclosing (Windoweven
                    T e) {try {if (socket!= null) socket.close ();
                    if (inputstream!= null) inputstream.close ();
                if (outputstream!= null) outputstream.close ();
                catch (IOException E1) {e1.printstacktrace ();
    }
            }
        }); @Override public void actionperformed (ActionEvent e) {if (e.getsource () = = Btnsend) {Send
        MSG ();
            }} private void Sendmsg () {try {String s = textfield.gettext (); if (!s.equals ("")) {//Send Data Textfield.settext ("");
                Textarea.append ("I (" + tfname.gettext () + "): \ r \ n" + S + "\ r \ n");
                OutputStream = new DataOutputStream (Socket.getoutputstream ()); 
                Outputstream.writeutf (Tfname.gettext () + "#" + s);
            Outputstream.flush ();
        } catch (IOException e) {e.printstacktrace (); @Override public void keypressed (KeyEvent arg0) {if (Arg0.getkeycode () = Keyevent.vk_enter)
        {sendmsg (); @Override public void keyreleased (KeyEvent arg0) {} @Override public void keytyped (Keyeven T arg0) {} @Override public void Run () {try {InputStream = new DataInputStream (socket

            . getInputStream ());
                while (true) {string[] s = Inputstream.readutf (). Split ("#");
            Textarea.append (S[0] + ": \ r \ n" + s[1] + "\ r \ n"); }
        } catch (IOException e) {}}} 

2. Server Interface Serviceview.java

public class Serviceview extends JFrame implements actionlistener{private JButton btnopen, btnstop;
    Private JLabel label;
    Private service service = NULL;
    public static arraylist<clientview> clientviews = new arraylist<> ();

    private static Serviceview view;
    public static Serviceview GetView () {return view;
    public static void Main (string[] args) {view = new Serviceview ();
    Public Serviceview () {Initview ();
        private void Initview () {btnopen = new JButton ("Open Server");
        Btnstop = new JButton ("Shut Down server");
        Btnstop.setenabled (FALSE);
        Btnopen.addactionlistener (this);
        Btnstop.addactionlistener (this);
        label = new JLabel ("Server stops working");
        Add (label);
        Add (Btnopen);
        Add (Btnstop);
        Settitle ("server");
        SetLayout (New GridLayout (3, 1, 0, 10));
        SetSize (300, 300);
        setlocation (450, 150);
        SetVisible (TRUE); SetdefAultcloseoperation (Exit_on_close); @Override public void actionperformed (ActionEvent e) {if (e.getsource () = = Btnopen) {Open
        ();
        else {stop ();
        } public void Open () {//Open Server service = new service ();
        Thread thread = new thread (service);
        Thread.Start ();
        Label.settext ("server is Running");
        Btnopen.setenabled (FALSE);
    Btnstop.setenabled (TRUE);
        public void Stop () {//Shut Down Server Label.settext ("server is closed");
        Btnopen.setenabled (TRUE);
        Btnstop.setenabled (FALSE); try {synchronized (clientmannager.sockets) {//close each connection for (Chatsocket Socket:clientmannager
                    . Sockets) {Socket.getinputstream (). Close ();
                Socket.getoutputstream (). Close ();
            } ClientMannager.sockets.removeAllElements ();
        for (Clientview view:clientviews) {        View.getinputstream (). Close ();
            View.getoutputstream (). Close ();
        } service.getserversocket (). Close ();
        catch (IOException e) {e.printstacktrace (); }
    }

}
Functional Class

1.chatsocket.java

* * Use socket to obtain data flow, to achieve the purpose of transmitting data/public class Chatsocket implements runnable{private socket socket = NULL;
    Private DataInputStream InputStream = null;

    Private DataOutputStream outputstream = null;
    Public DataInputStream getInputStream () {return inputstream;
    Public DataOutputStream Getoutputstream () {return outputstream;
        Public chatsocket (socket socket) {this.socket = socket;
            try {inputstream = new DataInputStream (Socket.getinputstream ());
        OutputStream = new DataOutputStream (Socket.getoutputstream ());
        catch (IOException e) {e.printstacktrace ();
            The public void Send (String send) {//Send data try {outputstream.writeutf (send) to the client;
        Outputstream.flush ();
        catch (IOException e) {e.printstacktrace ();

        @Override public void Run () {///loop reads the data sent by the client String accept = NULL; WHile (True) {try {accept = Inputstream.readutf ();
            Clientmannager.sendall (this, accept);
            catch (IOException e) {ClientMannager.sockets.remove (this); }
        }
    }
}

2.clientmannager.java

/* Client Manager *
/public class Clientmannager {

    private Clientmannager () {
    } public

    static vector< chatsocket> sockets = new vector<> ();

    Send data public
    static void Sendall (Chatsocket chatsocket, String send) to other clients {for
        (Chatsocket socket:sockets) { C7/>if (!chatsocket.equals (socket)) {
                socket.send (send);}}}

3.service.java

/* server-side, use thread to achieve the purpose of loop waiting for connection/public class Service implements runnable{private ServerSocket serv

    Ersocket = null;
    Public ServerSocket Getserversocket () {return serversocket;
            @Override public void Run () {try {serversocket = new ServerSocket (9090);//Create Port
                while (true) {///on-receiving client's connection socket socket = serversocket.accept ();
                Joptionpane.showmessagedialog (Serviceview.getview (), "Client connection port", "TIP", joptionpane.information_message); Chatsocket chatsocket = new Chatsocket (socket); New Client Connection ClientMannager.sockets.add (Chatsocket); Add Customer thread thread = new Thread (chatsocket) to the client manager;

            Enabling threading causes the server to start receiving client information Thread.Start ();
            } catch (IOException e) {e.printstacktrace ();
        SYSTEM.OUT.PRINTLN ("Server shutdown"); }
    }

}

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.