I've been quite idle recently and have been taking time to review some Java technical applications.
I have nothing to do today. Based on the UDP protocol, I wrote a very simple chat room program.
In my current work, sockets are rarely used, which is also a simple memory of Java network programming.
Let's take a look at the effect:
The effect of implementation can be said to be very, very simple, but you can still simply see an implementation principle.
Users of "Chat Room 001", Xiaohong and Xiaolu chatted with each other for a few words, and Xiaohei from "Chat Room 002" ignored him and was lonely.
Take a look at the code implementation:
1. First of all, the implementation of the message server, the function is very simple:
• Register the client's information (which chat room you entered, etc.);
•Construct UDP protocol socket object to accept messages sent by each client;
• Analyze the message content and push the chat information back to each client in the corresponding chat room;
package com.tsr.simplechat.receive_server;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;import java.util.ArrayList;import java.util.HashMap;import com.google.gson.Gson;import com.tsr.simplechat.bean.MessageEntity;import com.tsr.simplechat.client.ChatClient;//Chat Server public class ChatServer extends Thread { // The program occupies the port number private static final int PORT = 10000; // The message accepts socket object private static DatagramSocket server = null; // Dictionary object (Key: Chat room ID, Value: the set of client users under this chat room); private static HashMap<String, ArrayList<ChatClient>> groups = new HashMap<String, ArrayList<ChatClient>>(); // Constructor public ChatServer() { try { // The message accepts the construct initialization of the socket object server = new DatagramSocket(PORT); } catch (SocketException e) { e.printStackTrace(); } } // Register a new login user in the chat room public static void logInGroup(String groupID, ChatClient client) { // Get all online users of the chat room through the chat room ArrayList<ChatClient> clients = groups.get(groupID); if (clients == null) { clients = new ArrayList<ChatClient>(); } // Register the users who enter the chat room this time clients.add(client); // Update chat room information groups.put(groupID, clients); } // Receive message @Override public void run() { while (true) { receiveMessage(); } } private void receiveMessage() { // UDP packet byte[] buf = new byte[1024]; DatagramPacket packet = new DatagramPacket(buf, buf.length); while (true) { try { // Accept packet server.receive(packet); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // parse the data packet and obtain chat information String content = new String(packet.getData(), 0, packet.getLength()); // parse json data through third-party package Gson gson = new Gson(); MessageEntity me = gson.fromJson(content, MessageEntity.class); // parse the message content and obtain all online users of the chat room through the chat room ID ArrayList<ChatClient> clients = groups.get(me.getGroupId()); // push the received message back to each user of the chat room for (ChatClient client: clients) { client.pushBackMessage(me); } } }}2. The client program is still very simple:
•Simplely define the client chat room interface.
•Construct the message send socket object.
• Get the content of the chat information box and send it to the server.
package com.tsr.simplechat.client;import java.awt.Button;import java.awt.Event;import java.awt.Frame;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.SocketException;import java.net.UnknownHostException;import com.tsr.simplechat.bean.MessageEntity;import com.tsr.simplechat.receive_server.ChatServer;//Client program public class ChatClient extends Frame { private static final long serialVersionUID = 1L; // Chat room ID private String groupID; // Client username private String clientName; // Client message sending service socket private DatagramSocket msg_send; // Service port private final int PORT = 10000; // Server IP address private InetAddress ip; // Client control TextField tf = new TextField(20); TextArea ta = new TextArea(); Button send = new Button("send"); // Client constructor public ChatClient(String groupID, String clientName) { super("Chat room:" + groupID + "/" + clientName); this.clientName = clientName; this.groupID = groupID; // Set the client interface style add("North", tf); add("Center", ta); add("South", send); setSize(250, 250); show(); // Initialize init() for chat related servers; // Monitor addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { // Close the message sending service msg_send.close(); // Close the client program dispose(); System.exit(0); } }); } // Initialize private void init() { // Register the current user and chat room information to the server ChatServer.logInGroup(groupID, this); try { // Initialize the message sending socket object msg_send = new DatagramSocket(); // Specify the message server try { ip = InetAddress.getByName("127.0.0.1"); } catch (UnknownHostException e) { System.out.println("UnknownHostException.."); } } catch (SocketException e) { System.out.println("Socket connection exception.."); } } // Message sending button time listening public boolean action(Event evt, Object arg) { if (evt.target.equals(send)) { try { // Get input content String content = tf.getText(); // Send message send_message(content); // Clear chat box tf.setText(null); } catch (Exception ioe) { System.out.print(ioe.getMessage()); } } return true; } // Send message private void send_message(String content) { // Message format (json format) String message = messageFormat(content); // Encapsulate the message into UDP packet byte[] buf = message.getBytes(); DatagramPacket packet = new DatagramPacket(buf, buf.length, ip, PORT); try { // Send the message msg_send.send(packet); } catch (IOException e) { System.out.println("IO exception.."); } } // Message formatting private String messageFormat(String content) { StringBuffer buffer = new StringBuffer(); buffer.append("{/"groupId/":").append("/"").append(groupID).append( "/","); buffer.append("/"userName/":/").append(clientName).append("/","); buffer.append("/"text/":/").append(content).append("/"}"); return buffer.toString(); } // Get the latest news of the current chat room from the server (callback..) public void pushBackMessage(MessageEntity me) { ta.append(me.getUserName() + ":" + me.getText()); ta.append("/n"); }} 3. Message entity class <br />It is mainly used to encapsulate messages into objects, including: chat room ID, message sender nickname, and message content. Use json format to parse.
package com.tsr.simplechat.bean;//Message entity public class MessageEntity { private String groupId; private String userName; private String text; public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getText() { return text; } public void setText(String text) { this.text = text; }}4. OK, it’s basically done here, and create a test class.
• Turn on the message server.
•Open three clients, two of which enter "Chat Room 001" and the other enter "Chat Room 002".
import com.tsr.simplechat.client.ChatClient;import com.tsr.simplechat.receive_server.ChatServer;public class Test { public static void main(String[] args) { ChatServer r = new ChatServer(); r.start(); ChatClient c1 = new ChatClient("001", "Little Red"); ChatClient c2 = new ChatClient("001", "Little Green"); ChatClient c3 = new ChatClient("002", "Little Black"); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.