ImportJava.io.*;Importjavax.swing.*;Importjava.net.*;Importjava.awt.*;Importjava.awt.event.*; Public classSimplechatclienta {JTextArea incoming; BufferedReader reader; Socket sock; JTextField outgoing; PrintWriter writer; //Build the interface Public voidGo () {JFrame frame=NewJFrame ("Gaby ' s specific chatclient"); JPanel Mainpanel=NewJPanel (); /*here is a bunch of GUI components incoming and JScrollPane settings * I'm ignoring*/Outgoing=NewJTextField (20); JButton Sendbutton=NewJButton ("Send"); Mainpanel.add (outgoing); Mainpanel.add (Sendbutton); Sendbutton.addactionlistener (NewButtonlistener ()); Frame.getcontentpane (). Add (Borderlayout.center, Mainpanel); Setupnetworking (); Thread T=NewThread (NewIncomingreader ()); T.start (); Frame.setsize (300, 400); Frame.setvisible (true); } //build the link between the class and the server Public voidsetupnetworking () {Try{sock=NewSocket ("192.168.0.105", 5000); InputStreamReader StreamReader=NewInputStreamReader (Sock.getinputstream ()); Reader=NewBufferedReader (StreamReader); Writer=NewPrintWriter (Sock.getoutputstream ()); System.out.println ("Networking established"); }Catch(Exception ex) {ex.printstacktrace (); } } //Register to a button and send message to server classButtonlistenerImplementsactionlistener{ Public voidactionperformed (ActionEvent ev) {writer.println (Outgoing.gettext ());//because output, only wait until the buffer is full before output, some time the content of the output is relatively small, not filled with buffers, will not be output immediately. Writer.flush (); } } //runnable class uses multithreading Public classIncomingreaderImplementsrunnable{String message; Public voidrun () {Try{ while(message = Reader.readline ())! =NULL) {System.out.println ("Read" +message); Incoming.append (Message+ "\ n"); } }Catch(Exception ex) {ex.printstacktrace (); } } } //Main Public Static voidMain (String args[]) {Simplechatclienta client=NewSimplechatclienta (); Client.go (); }}
View Simplechatclient.java
The program can be divided into the following function blocks:
- Go
- Setupnetworking
- Buttonlistener implements ActionListener
- Incomingreader Implements Runnable
Go
Used to build the GUI, call Setupnetworking (), and start a new line for receiving server information
Setupnetworking:
By having the socket Sock act as an instance variable for this object, its lifetime is accompanied by the entire program
Also, set up reader and writer.
Buttonlistener Implements ActionListener (inner Class):
In go, register the listener with the button, if you encounter click, it is handled by the Buttonlistener object, the processing method is to send information to the server, meaning that writer is an instance variable
Incomingreader Implements Runnable (inner Class):
The run function inside is the content of the new thread, and therefore uses the reader of the external class object.
Simple Chat client program