Java online Chat Item resolves a problem when the client sends information to the server OutputStreamWriter DataOutputStream Socket.getoutputstream ()

Source: Internet
Author: User
Tags gettext

The client code is not resolved before the problem:

 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.BufferedWriter;ImportJava.io.DataOutputStream;Importjava.io.IOException;ImportJava.io.OutputStreamWriter;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 classChatClientFrame2extendsJFrame {Private Static Final LongSerialversionuid = -118470059355655240l; Socket s=NULL; JLabel Label_shang=NewJLabel (); JLabel Label_xia=NewJLabel (); JTextField TF=NewJTextField (38); JTextArea Ta=NewJTextArea (15, 50); JButton Button=NewJButton ();  PublicChatClientFrame2 () {setbounds (200, 200, 500, 400); Settitle ("Client Chat tool--0.4"); //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); /** Three panels, put a label "chat history", put a text field in the middle, * the bottom is divided into left and right--put the label "input Information", text box and "Send" button*/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); /** Add the function of "Send" button, increase the function of carriage return, monitor the same, * use inner class implementation to improve code reusability*/        Final classSharelistenerImplementsactionlistener{@Override Public voidactionperformed (ActionEvent e) {String Tatext=Ta.gettext (); String Tftext=tf.gettext () + "\ r \ n"; Ta.settext (Tatext+tftext); Tf.settext (""); //when the carriage return or send button is Tftext sent to the server                Try {                    //you can try using the writeUTF method in DataOutputStream.//dataoutputstream ds=new DataOutputStream (S.getoutputstream ());//Ds.writeutf (tftext);//Ds.flush ();//ds.close ();BufferedWriter bw=NewBufferedWriter (NewOutputStreamWriter (S.getoutputstream (), "Utf-8"));                    Bw.write (Tftext);                Bw.close (); } Catch(IOException E1) {//TODO auto-generated Catch blockE1.printstacktrace (); }}} Button.addactionlistener (NewSharelistener ()); Tf.addactionlistener (NewSharelistener ()); //Auto-Adjust individual panels with compressionpack (); Setdefaultcloseoperation (jframe.exit_on_close);//Click the Close button while exiting the programSetVisible (true); //Create a form to call the connection server directlyConnect (); }        /** Add a method to connect to the server*/     Public voidConnect () {Try{s=NewSocket ("127.0.0.1", 8888); System.out.println ("Connected!"); } Catch(unknownhostexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }         Public Static voidMain (string[] args) {//don't forget to create a Form object, or you can call other methods with a build object such as Launchframe ()        NewChatClientFrame2 (); }}

The service-side code is not resolved before the problem:

 PackageCom.swift;ImportJava.io.BufferedReader;ImportJava.io.DataInputStream;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classChatserver { Public Static voidMain (string[] args) {Try{ServerSocket ss=NewServerSocket (8888);  for (;;) {Socket s=ss.accept (); //when there is a connection, it is displayed for testingSYSTEM.OUT.PRINTLN ("A client connected success"); //you can try using the readUTF method in DataInputStream//datainputstream dis=new DataInputStream (S.getinputstream ());//String Str=dis.readutf ();//dis.close ();bufferedreader BR=NewBufferedReader (NewInputStreamReader (S.getinputstream (), "Utf-8")); String Str=Br.readline ();            System.out.println (str); }        } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }}

Presentation process

A problem occurred:

Java.net.SocketException:Socket is closed

Java online Chat Item resolves a problem when the client sends information to the server OutputStreamWriter DataOutputStream Socket.getoutputstream ()

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.