Use Java socket to do a chat room, to achieve the function of many people chat.

Source: Internet
Author: User
Tags addgroup gettext sendmsg

Use Java socket to do a chat room, to achieve the function of many people chat. Watched the Geek College video and then knocked on it. (1DAY)
Service side:
1. First write the service end of the class myServerSocket, which put a listening thread, a start on the good
2. Implementation of the service-side listening class Serverlistener.java, with accept to monitor, once a client connected, generate a new socket, the new thread instance Chatsocket. When the thread is started, the thread is handed over to Chatmanager management
3. In Chatsocket to read from the client content, read the content to the collection of all the clients
4. Chatmanager inside uses vector to manage socket thread instance Chatsocket, and implements sending information to other clients

Client:
1. Create a new Mainwindow.java class that inherits JFrame, mainly implement the UI of the Chat window, and the event response.
2. Create a new Startclient.java class, MainWindow the MainWindow Main method part of the code to copy it, so you can execute the form in the main program.
3. Create a new Chatmanager (require a single instance of the class) to manage the socket, to achieve the input and output function chat. Finally remember in 1 after the new window, pass a frame reference to Chatmanager, in order to achieve Chatmanager interface display.

Engineering structure as shown

Following is the code
Service side:
1. First write the service end of the class myServerSocket, which put a listening thread, a start on the good

Package com.starnet.testserversocket.main;


public class myServerSocket {public
    static void Main (string[] args) {
        new Serverlistener (). Start ();

2. Implementation of the service-side listening class Serverlistener.java, with accept to monitor, once a client connected, generate a new socket, the new thread instance Chatsocket. When the thread is started, the thread is handed over to Chatmanager management

Package com.starnet.testserversocket.main;

Import java.io.IOException;
Import Java.net.ServerSocket;
Import Java.net.Socket;

Import Javax.swing.JOptionPane;

public class Serverlistener extends Thread {public
    void run () {
        try {
            ServerSocket serversocket = new ServerS Ocket (23456);
            while (true) {
                //block
                socket socket = serversocket.accept ();
                Establish link 
                joptionpane.showmessagedialog (NULL, "Client connected to native 23456 port");
                Pass the socket to the new thread,
                chatsocket cs= (socket);
                Cs.start ();
                Chatmanager.getchatmanager (). Add (CS);
            }
        } catch (IOException e) {
            e.printstacktrace ();}}}

3. Implement the Read content from the client in Chatsocket and send the read content to all the clients in the collection

Package com.starnet.testserversocket.main;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import java.io.UnsupportedEncodingException;
Import Java.net.Socket;

    /* Each connected client, the server has a thread for the service * * public class Chatsocket extends thread {socket socket;
    Public Chatsocket (Socket s) {this.socket = s; //Send data public void out (String out) {try {socket.getoutputstream (). Write (Out.getbytes ("UTF
        -8 ")); 
        catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
    }//The server will constantly read from the client and send the read content to all the clients in the collection.
                    public void Run () {try {//Receive data BufferedReader br = new BufferedReader ( New InputStreamReader (Socket.getinputstream (), "UTF-8 "));
            String Line=null;
                Sends the Read content while (line = Br.readline ())!=null) {System.out.println (line);
            Chatmanager.getchatmanager (). Publish (this, line);
        } br.close ();
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
 }
    }
}

4.ChatManager inside the vector to manage the socket thread instance chatsocket, and the implementation of sending information to other clients

Package com.starnet.testserversocket.main;

Import Java.util.Vector;
A chat server can only have one manager, to single handle public
class Chatmanager {
    private Chatmanager () {}
    private static final Chatmanager cm=new Chatmanager ();
    public static Chatmanager Getchatmanager () {return
        CM;
    }

    vector<chatsocket> vector = new vector<chatsocket> ();
    /* Add Chatsocket instance to vector */public
    void Add (Chatsocket cs) {
        vector.add (CS);
    }

    /* Publish message to other clients
     *chatsocket CS: Call Publish thread
     *msg: Message to send/public
    void Publish (Chatsocket cs, String msg) {for
        (int i = 0; i < vector.size (); i++) {
            Chatsocket cstemp = Vector.get (i);
            if (!cs.equals (cstemp)) {
                cstemp.out (msg+ "\ n");/do not send to yourself.
            }
        }
    }

}

Client:
1. Create a new Mainwindow.java class that inherits JFrame, mainly implement the UI of the Chat window, and the event response.

Package Com.starnet.javaclient.view;
Import Java.awt.BorderLayout;

Import Java.awt.EventQueue;
Import Javax.swing.JFrame;
Import Javax.swing.JPanel;
Import Javax.swing.border.EmptyBorder;
Import Javax.swing.JTextArea;
Import Javax.swing.GroupLayout;
Import javax.swing.GroupLayout.Alignment;
Import Javax.swing.JTextField;
Import Javax.swing.JButton;

Import javax.swing.LayoutStyle.ComponentPlacement;
Import Com.starnet.javaclient.main.ChatManager;

Import com.sun.xml.internal.ws.client.SenderException;
Import Java.awt.event.MouseAdapter;

Import java.awt.event.MouseEvent;
    public class MainWindow extends JFrame {/** * */private static final long serialversionuid = 1L;
    Private JPanel ContentPane;
    Private JTextArea txt;
    Private JTextField Txtip;

    Private JTextField Txtsend;
     /** * Create the frame.
        */Public MainWindow () {setalwaysontop (true);
        Setdefaultcloseoperation (Jframe.exit_on_close); SetBounds (100, 100, 450, 300);
        ContentPane = new JPanel ();
        Contentpane.setborder (New Emptyborder (5, 5, 5, 5));

        Setcontentpane (ContentPane);
        txt = new JTextArea ();

        Txt.settext ("Ready ...");
        Txtip = new JTextField ();
        Txtip.settext ("127.0.0.1");

        Txtip.setcolumns (10);
        JButton btnconnect = new JButton ("Connect"); Btnconnect.addmouselistener (New Mouseadapter () {@Override public void mouseclicked (MouseEvent e)
            {Chatmanager.getchatmanager (). Connect (Txtip.gettext ());

        }
        });
        Txtsend = new JTextField ();
        Txtsend.settext ("Hello");

        Txtsend.setcolumns (10);
        JButton btnsend = new JButton ("send");
                Btnsend.addmouselistener (New Mouseadapter () {@Override public void mouseclicked (MouseEvent e) {
                Chatmanager.getchatmanager (). Send (Txtsend.gettext ());
 AppendText ("I said:" +txtsend.gettext ());               Txtsend.settext ("");
        }
        });
        Grouplayout Gl_contentpane = new Grouplayout (ContentPane); Gl_contentpane.sethorizontalgroup (Gl_contentpane.createparallelgroup (alignment.leading). AddG Roup (alignment.trailing, Gl_contentpane.createsequentialgroup (). AddGroup (Gl_contentpane.createparalle
                            Lgroup (alignment.trailing). AddGroup (Gl_contentpane.createsequentialgroup () . addcomponent (Txtsend, grouplayout.default_size, 325, Short.max_value). Addpreferredgap ( componentplacement.related). AddComponent (Btnsend, Grouplayout.preferred_size, 109, grouplayou
                            t.preferred_size)). AddGroup (Alignment.leading, Gl_contentpane.createsequentialgroup ()
                            . addcomponent (Txtip, Grouplayout.preferred_size, 294, grouplayout.preferred_size) . addPreferredgap (componentplacement.related). AddComponent (Btnconnect, grouplayout.default_size, 1
                    (Short.max_value)). addcomponent (TXT, grouplayout.default_size, 434, Short.max_value))
        . Addcontainergap ()); Gl_contentpane.setverticalgroup (Gl_contentpane.createparallelgroup (alignment.leading). AddGro Up (Gl_contentpane.createsequentialgroup (). AddGroup (Gl_contentpane.createparallelgroup (Alignment.BASEL INE). AddComponent (Txtip, Grouplayout.preferred_size, Grouplayout.default_size, Grouplayout.prefer red_size). AddComponent (Btnconnect)). Addpreferredgap (Componentplacement.relat ED). addcomponent (TXT, grouplayout.default_size, 198, short.max_value). Addpreferr Edgap (componentplacement.related). AddGroup (Gl_contentpane.createparallelgrOUP (alignment.trailing). AddComponent (Btnsend). AddComponent (Txtsend, Grou
        Playout.preferred_size, Grouplayout.default_size, grouplayout.preferred_size)));
    Contentpane.setlayout (Gl_contentpane);
    /* The content sent by the client is added to the middle TXT control/public void AppendText (String in) {txt.append ("\ n" + in);
 }
}

2. Create a new Startclient.java class, MainWindow the MainWindow Main method part of the code to copy it, so you can execute the form in the main program.

Package com.starnet.javaclient.main;

Import Java.awt.EventQueue;

Import Com.starnet.javaclient.view.MainWindow;

public class Startclient {public
    static void Main (string[] args) {/
        * Create a new JFrame first, and then post
        the automatically generated code. Eventqueue.invokelater (New Runnable () {public
            void run () {
                try {
                    MainWindow frame = new MainWindow ();
                    Frame.setvisible (true);
                    After creating this frame, pass a reference to the window to Chatmanager to
                    Chatmanager.getchatmanager (). Setwindow (frame);
                } catch ( Exception e) {
                    e.printstacktrace ();}}
        );
}

3. Create a new Chatmanager (require a single instance of the class) to manage the socket, to achieve the input and output function chat. Finally remember in 1 after the new window, pass a frame reference to Chatmanager, in order to achieve Chatmanager interface display.

Package com.starnet.javaclient.main;
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.net.UnknownHostException;

Import Com.starnet.javaclient.view.MainWindow;
    public class Chatmanager {private Chatmanager () {} private static final Chatmanager instance=new Chatmanager ();
    public static Chatmanager Getchatmanager () {return instance;
    MainWindow window;//in order to be able to display the server in the interface information sent, you need to pass a MainWindow reference in the socket socket;
    Private String IP;
    BufferedReader Breader;
    PrintWriter pwriter;
        public void Setwindow (MainWindow window) {this.window = window;
    Window.appendtext ("text box already bound with Chatmanager"); public void Connect (String IP) {this.
        ip = IP;
                    New Thread () {@Override public void run () {//Implement network method try {Socket = new Socket (IP, 23456);
                                    Output stream pwriter = new PrintWriter (New OutputStreamWriter (
                    Socket.getoutputstream ()));
                                    Input stream breader = new BufferedReader (New InputStreamReader (

                    Socket.getinputstream ()));
                    String line = null; If the read data is an empty while (line = Breader.readline ())!=null {Window.appendtext Received:
                    "+line);
                    After reading the data to close pwriter.close ();
                    Breader.close ();
                    Pwriter = null;

                Breader = null;
                catch (Unknownhostexception e) {e.printstacktrace ();
                catch (IOException e) {e.printstacktrace ();
   }         }}.start ();
            public void Send (String sendmsg) {if (pwriter!=null) {pwriter.write (sendmsg+ "\ n");
        Pwriter.flush ();
        else {window.appendtext ("Current link interrupted ...");
 }
    }
}
Related Article

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.