I recently started a project where there is a need for online web communication. I haven't written code for a long time and I'm unfamiliar with it. So I first wrote a demo and practiced it and shared it on the Wulin Network platform to make a record so that it can be used with everyone.
Let me first tell you the implementation steps:
1. Use awt component and socket to implement a simple single client to continuously send messages to the server;
2. Combined with threads, realize multi-client connection to the server to send messages;
3. Implement the server forwarding client messages to all clients and display them on the client at the same time;
4. Change the window interface generated by the awt component to the interface displayed by front-end jsp or html, and change the client implemented by java socket to the front-end technology implementation.
Here we first implement the simple function of the first step, the difficulty is:
1. I have never used the awt component and I have never used java-related listening events;
2. I have not used sockets for long periods of time to interact between the client and the server, and I have not really developed the CSS structure.
The code to implement the function is as follows:
Client:
package chat.chat; import java.awt.BorderLayout; import java.awt.Frame; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; /** * Online chat client 1. Generate graphical window interface outline 2. Add a close event to the outline 3. Add an input area and a content display area to the outline 4. Add a carriage return event for the input area* 5. Establish a server connection and send data* * @author tuzongxun123 * */ public class ChatClient extends Frame { // User input area private TextField tfTxt = new TextField(); // Content display area private TextArea taste = new TextArea(); private Socket socket = null; // Data output stream private DataOutputStream dataOutputStream = null; public static void main(String[] args) { new ChatClient().launcFrame(); } /** * Create a simple graphical window* * @author: tuzongxun * @Title: launcFrame * @param * @return void * @date May 18, 2016 9:57:00 AM * @throws */ public void launcFrame() { setLocation(300, 200); this.setSize(200, 400); add(tfTxt, BorderLayout.SOUTH); add(tarea, BorderLayout.NORTH); pack(); // Listen to the closing event of the graphical interface window this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); disConnect(); } }); tfTxt.addActionListener(new TFLister()); setVisible(true); connect(); } /** * Connect to the server* * @author: tuzongxun * @Title: connect * @param * @return void * @date May 18, 2016 9:56:49 AM * @throws */ public void connect() { try { // Create a new server connection socket = new Socket("127.0.0.1", 8888); // Get client output stream dataOutputStream = new DataOutputStream(socket.getOutputStream()); System.out.println("Connect to the server"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Close client resources* * @author: tuzongxun * @Title: disConnect * @param * @return void * @date May 18, 2016 9:57:46 AM * @throws */ public void disConnect() { try { dataOutputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Send a message to the server* * @author: tuzongxun * @Title: sendMessage * @param @param text * @return void * @date May 18, 2016 9:57:56 AM * @throws */ private void sendMessage(String text) { try { dataOutputStream.writeUTF(text); dataOutputStream.flush(); } catch (IOException e1) { e1.printStackTrace(); } } /** * Graphics window input area to listen for carriage return event* * @author tuzongxun123 * */ private class TFLister implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String text = tfTxt.getText().trim(); taxa.setText(text); tfTxt.setText(""); // Send data to the server sendMessage(text); } } }Server:
package chat.chat; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; /** * java uses socket and awt components to simply implement the online chat function. The server can realize the server connection to continuously send messages to the server after one client is connected* but does not support multiple clients to connect at the same time. The reason is that after obtaining the client connection in the code, it will keep listening to client inputs looped, causing blockage* so that the server cannot listen to another client twice. If you want to implement it, you need to use asynchronous or multithreaded* * @author tuzongxun123 * */ public class ChatServer { public static void main(String[] args) { // Whether the server is started successfully boolean isStart = false; // Server socket ServerSocket ss = null; // Client socket Socket socket = null; // Server read client data input stream DataInputStream dataInputStream = null; try { // Start server ss = new ServerSocket(8888); } catch (BindException e) { System.out.println("Port is already in use"); // Close the program System.exit(0); } catch (Exception e) { e.printStackTrace(); } try { isStart = true; while (isStart) { boolean isConnect = false; // Start the listening socket = ss.accept(); System.out.println("one client connect"); isConnect = true; while (isConnect) { // Get the client input stream dataInputStream = new DataInputStream( socket.getInputStream()); // Read the data passed by the client String message = dataInputStream.readUTF(); System.out.println("Client says: " + message); } } } catch (EOFException e) { System.out.println("client closed!"); } catch (Exception e) { e.printStackTrace(); } finally { // Close the related resource try { dataInputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }The above is the relevant knowledge about Java Socket implementing a simple online chat function (I) introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!