This article shares an example to meet the needs of online web communication. Due to the web version of online chat function implemented by java Socket, for your reference, the specific content is as follows
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.
Code to implement the function :
Online Chat Client:
1. Generate graphical window interface outline
2. Add a close event to the outline
3. Add input area and content display area to the outline
4. Add a carriage return event to the input area
5. Establish a server connection and send data
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 to continuously send messages to the server after connecting one client* 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(); } } } }Continue, based on a single client connection, the second step here requires the implementation of multiple client connections, which requires the use of threads. Whenever a new client connects, the server needs to start a new thread for processing, thereby solving the problem of blocking in previous loop readings.
There are usually two methods for writing threads: integrating Thread or implementing runnable interface. In principle, if runnable can be implemented, it will not be inherited because the way to implement the interface is more flexible.
The client code has not changed compared to before and has become a server, so only the server code is posted here:
Java uses socket and awt components and multi-threading to simply implement the online chat function server:
After multiple clients are connected, messages are continuously sent to the server. Compared with the first version, the focus is on using multi-threading. The server has not yet implemented the forwarding function. The client can only see the information entered by itself in the graphics window, and cannot see the messages sent by other clients.
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; import java.net.SocketException; /** * * * @author tuzongxun123 * */ public class ChatServer { public static void main(String[] args) { new ChatServer().start(); } // Whether the server is started successfully private boolean isStart = false; // server socket private ServerSocket ss = null; // client socket private Socket socket = null; public void start() { try { // start server ss = new ServerSocket(8888); } catch (BindException e) { System.out.println("Port is in use"); // Close the program System.exit(0); } catch (Exception e) { e.printStackTrace(); } try { isStart = true; while (isStart) { // Start listening socket = ss.accept(); System.out.println("one client connect"); // Start client thread Client client = new Client(socket); new Thread(client).start(); } } catch (Exception e) { e.printStackTrace(); } finally { // Close the service try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Client thread* * @author tuzongxun123 * */ class Client implements Runnable { // Client socket private Socket socket = null; // Client input stream private DataInputStream dataInputStream = null; private boolean isConnect = false; public Client(Socket socket) { this.socket = socket; try { isConnect = true; // Get client input stream dataInputStream = new DataInputStream(socket.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { isConnect = true; try { while (isConnect) { // 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 (SocketException e) { System.out.println("Client is Closed!!!"); } catch (Exception e) { e.printStackTrace(); } finally { // Close the relevant resource try { dataInputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }The above mainly introduces the function of using threads to enable the server to receive multi-client requests. Here, the client needs to receive multi-client messages while forwarding messages to each connected client, and the client must be able to display them in the content display area, thereby realizing a simple online group chat.
When implementing client forwarding, it is nothing more than increasing the output stream; before, the client only sent but not received it, so it also needs to change the client to receive server messages in a circular manner, so it also needs to implement multi-threading.
When implementing this function, I accidentally remembered the function of randomly generating verification codes, so I had a sudden inspiration to randomly generate a name for each client, so that when outputting, it looks more like a group chat, not only has message output, but also can see who it is.
After implementing these functions, you can basically have a group chat online at the same time for several people. Because there is a main method in the code, you can make both the server and the client into executable jar packages. You can refer to another blog post of mine: Use eclipse to create a Java program executable jar package.
Then double-click the corresponding jar file on the desktop to start the server and client, and you no longer need to rely on eclipse to run.
The modified client code is as follows:
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.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.util.Random; /** * Online chat client steps: *1. Generate graphical window interface outline*2. Add a close event for the outline*3. Add an input area and a content display area in 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 { /** * */ private static final long serialVersionUID = 1L; // 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; // Data input stream private DataInputStream dataInputStream = null; private boolean isConnect = false; Thread tReceive = new Thread(new ReceiveThread()); String name = ""; public static void main(String[] args) { ChatClient chatClient = new ChatClient(); chatClient.createName(); 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); // Determine the optimal size of the frame according to the layout in the window and the preferredSize of the components 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()); // Set the window to see setVisible(true); connect(); // Start the thread that accepts the message tReceive.start(); } /** * 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()); dataInputStream = new DataInputStream(socket.getInputStream()); System.out.println("Connect to the server"); isConnect = true; } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // Generate random client name public void createName() { String[] str1 = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; Random ran = new Random(); for (int i = 0; i < 6; i++) { // long num = Math.round(Math.random() * (str1.length - 0) + 0); // int n = (int) num; int n = ran.nextInt(str1.length); if (n < str1.length) { String str = str1[n]; name = name + str; System.out.println(name); } else { i--; continue; } } this.setTitle(name); } /** * Close client resources* * @author: tuzongxun * @Title: disConnect * @param * @return void * @date May 18, 2016 9:57:46 AM * @throws */ public void disConnect() { try { isConnect = false; // Stop thread tReceive.join(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { if (dataOutputStream != null) { dataOutputStream.close(); } if (socket != null) { socket.close(); socket = null; } } 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(name + ":" + text); dataOutputStream.flush(); } catch (IOException e1) { e1.printStackTrace(); } } /** * Graphic window input area listening carriage return event* * @author tuzongxun123 * */ private class TFLister implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String text = tfTxt.getText().trim(); // Clear the input area information tfTxt.setText(""); // Send the data to the server after pressing the carriage to sendMessage(text); } } private class ReceiveThread implements Runnable { @Override public void run() { try { while (isConnect) { String message = dataInputStream.readUTF(); System.out.println(message); String txt = taxa.getText(); if (txt != null && !"".equals(txt.trim())) { message = taxa.getText() + "/n" + message; } taxa.setText(message); } } catch (IOException e) { e.printStackTrace(); } } } } The modified server code is as follows:
package chat.chat; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List; /** * java uses socket and awt components and multi-threading to simply implement the online chat function server: * The server implements that the received client information is forwarded to all connected clients, and allows the client to read this information and display it in the content display area. * * @author tuzongxun123 * */ public class ChatServer { public static void main(String[] args) { new ChatServer().start(); } // Whether the server is successfully started private boolean isStart = false; // Server socket private ServerSocket ss = null; // Client socket private Socket socket = null; // Save client collection List<Client> clients = new ArrayList<Client>(); public void start() { try { // Start the server ss = new ServerSocket(8888); } catch (BindException e) { System.out.println("Port is in use"); // Close the program System.exit(0); } catch (Exception e) { e.printStackTrace(); } try { isStart = true; while (isStart) { // Start the listening socket = ss.accept(); System.out.println("one client connect"); // Start the client thread Client client = new Client(socket); new Thread(client).start(); clients.add(client); } } catch (Exception e) { e.printStackTrace(); } finally { // Close the service try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Client thread* * @author tuzongxun123 * */ private class Client implements Runnable { // Client socket private Socket socket = null; // Client input stream private DataInputStream dataInputStream = null; // Client output stream private DataOutputStream dataOutputStream = null; private boolean isConnect = false; public Client(Socket socket) { this.socket = socket; try { isConnect = true; // Get client input stream dataInputStream = new DataInputStream(socket.getInputStream()); // Get client output stream dataOutputStream = new DataOutputStream( socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } /** * Bulk send (forward) data to the client* * @author: tuzongxun * @Title: sendMessageToClients * @param @param message * @return void * @date May 18, 2016 11:28:10 AM * @throws */ public void sendMessageToClients(String message) { try { dataOutputStream.writeUTF(message); } catch (SocketException e) { } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { isConnect = true; Client c = null; try { while (isConnect) { // Read the data passed by the client String message = dataInputStream.readUTF(); System.out.println("The client says: " + message); for (int i = 0; i < clients.size(); i++) { c = clients.get(i); c.sendMessageToClients(message); } } } catch (EOFException e) { System.out.println("client closed!"); } catch (SocketException e) { if (c != null) { clients.remove(c); } System.out.println("Client is Closed!!!"); } catch (Exception e) { e.printStackTrace(); } finally { // Close the relevant resource try { if (dataInputStream != null) { dataInputStream.close(); } if (socket != null) { socket.close(); socket = null; } } catch (IOException e) { e.printStackTrace(); } } } } } } } } } } } } } } } } } } } }Let’s introduce it to you first, and then update it for you if there is any new content.
Regarding the realization of the web online chat function, you can also refer to the following articles for learning:
Java implements a simple TCPSocket chat room function sharing
The above is all the content of this article. I hope it will be helpful to everyone's learning, and I hope you can continue to pay attention to more exciting content from Wulin.com.