Java Online chat project version 0.6 resolves an exception problem after a client shutdown Dis.readutf () loops through the closed socket

Source: Internet
Author: User
Tags gettext try catch

The service side re-defines the try catch Finally, when an exception occurs, the active prompt, or the closing of the socket where the exception occurred

The server-side code is modified as follows:

 PackageCom.swift;ImportJava.io.DataInputStream;Importjava.io.IOException;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classChatserver { Public Static voidMain (string[] args) {BooleanStarted=false; ServerSocket SS=NULL; DataInputStream Dis=NULL; Socket s=NULL; Try{SS=NewServerSocket (8888); Started=true; } Catch(IOException E1) {//TODO auto-generated Catch blockE1.printstacktrace (); }        Try {             while(started) {BooleanConnected=false; S=ss.accept (); Connected=true; System.out.println ("A client connected success"); Dis=NewDataInputStream (S.getinputstream ());  while(connected) {String str=Dis.readutf ();                System.out.println (str); }            }        } Catch(Exception e) {//e.printstacktrace ();SYSTEM.OUT.PRINTLN ("client has closed."); }finally {            if(dis!=NULL) {                Try{dis.close (); } Catch(IOException e) {e.printstacktrace (); }            }            if(s!=NULL) {                Try{s.close (); } Catch(IOException e) {e.printstacktrace (); }            }        }    }}

The client has changed a OutputStream, uses DataOutputStream to send the message, Dos.writeutf (Tf.gettext ());

Version 0.6

The client code is modified as follows:

 PackageCom.swift;Importjava.awt.BorderLayout;ImportJava.awt.Color;Importjava.awt.event.ActionEvent;ImportJava.awt.event.ActionListener;ImportJava.awt.event.WindowAdapter;Importjava.awt.event.WindowEvent;ImportJava.io.DataOutputStream;Importjava.io.IOException;ImportJava.net.Socket;Importjava.net.UnknownHostException;ImportJavax.swing.JButton;ImportJavax.swing.JFrame;ImportJavax.swing.JLabel;ImportJavax.swing.JPanel;ImportJavax.swing.JScrollPane;ImportJavax.swing.JTextArea;ImportJavax.swing.JTextField; Public classChatclientframeextendsJFrame {Private Static Final LongSerialversionuid = -118470059355655240l; Socket s=NULL; DataOutputStream dos=NULL; JLabel Label_shang=NewJLabel (); JLabel Label_xia=NewJLabel (); JTextField TF=NewJTextField (38); JTextArea Ta=NewJTextArea (15, 50); JButton Button=NewJButton ();  PublicChatclientframe () {setbounds (200, 200, 500, 400); Settitle ("Client Chat tool--0.6"); //Large layout of the window, divided into three rows and a column, add three panels on the pbasic panel Shang Zhong XiaJPanel pbasic=NewJPanel (); Pbasic.setlayout (NewBorderLayout ());//This layout mode is also not set by defaultSetcontentpane (Pbasic);//Put the Panel on the window, do not remember to use the This keywordJPanel shang=NewJPanel (); JPanel Zhong=NewJPanel (); JPanel Xia=NewJPanel (); //to set the size of the JPanel panelShang.setsize (470, 25); Zhong.setsize (470, 180); Xia.setsize (470, 40);        Pbasic.add (Shang,borderlayout.north);        Pbasic.add (Zhong,borderlayout.center);        Pbasic.add (Xia,borderlayout.south);        Shang.setbackground (color.red);        Zhong.setbackground (Color.yellow);        Xia.setbackground (Color.Blue); Label_shang.settext ("Chat History");        Shang.add (Label_shang); Ta.setlinewrap (true);//Wrap LineJScrollPane scroll=NewJScrollPane (TA);//increase the scrollbar so that the number of rows is not increasedZhong.add (scroll); Label_xia.settext ("Enter Information");        Xia.add (label_xia,borderlayout.west); /** Added function, Window Listener event, window open when setting cursor focus in tf text field*/         This. Addwindowlistener (NewWindowadapter () {@Override Public voidwindowopened (windowevent e) {tf.requestfocus ();        }        });        Xia.add (Tf,borderlayout.center); Button.settext (Send);        Xia.add (Button,borderlayout.east); Final classSharelistenerImplementsactionlistener{@Override Public voidactionperformed (ActionEvent e) {String Tatext=Ta.gettext (); String Tftext=tf.gettext () + "\ r \ n"; String TfText1=Tf.gettext (); Ta.settext (Tatext+tftext); Tf.settext (""); //when the carriage return or send button is Tftext sent to the server                Try{Dos.writeutf (TFTEXT1);                Dos.flush (); } Catch(IOException E1) {e1.printstacktrace (); }}} Button.addactionlistener (NewSharelistener ()); Tf.addactionlistener (NewSharelistener ()); //Auto-Adjust individual panels with compressionpack ();  This. Addwindowlistener (NewWindowadapter () {@Override Public voidwindowclosing (windowevent e) {disconnect (); System.exit (0);        }        }); SetVisible (true); //Create a form to call the connection server directlyConnect (); }         Public voidConnect () {Try{s=NewSocket ("127.0.0.1", 8888); System.out.println ("Connected!"); DOS=NewDataOutputStream (S.getoutputstream ()); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }     Public voidDisconnect () {Try{dos.close ();        S.close (); } Catch(IOException e) {e.printstacktrace (); }    }             Public Static voidMain (string[] args) {NewChatclientframe (); }}

Java Online chat project version 0.6 resolves an exception problem after a client shutdown Dis.readutf () loops through the closed socket

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.