Use socket technology to implement online chat room and private chat functions, the specific content is as follows
Without further ado, let’s get the picture:
1. Chat room group chat page
Contact list for online users
socket connection page
Private chat page
Project Introduction
Implement socket connection with the server: When each client connects to the server, the server will save each connected socket in the list collection.
Group chat function: When a user sends a group chat message to the server, the server forwards all information to all connected clients in the list list.
Private chat function: After the user sends private chat information to the server, the server will send a message to a target IP.
Display the online contact list: When a new user logs in successfully, the server will send the online contact information to the client in the form of a json string, and the client obtains the online contact information by parsing the json string.
Customize a powerful class SocketEvent: The client communicates with the server and saves data through this class, and then use the fastjson tool to convert the class object into a json string for transmission.
public class SocketEvent { private int type =0; private String msg =""; private String keyIP =""; // Key IP private String temporaryIP =""; // Temporary IP public SocketEvent() { } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getKeyIP() { return keyIP; } public void setKeyIP(String keyIP) { this.keyIP = keyIP; } public String getTemporaryIP() { return temporaryIP; } public void setTemporaryIP(String temporaryIP) { this.temporaryIP = temporaryIP; }}type: Sign what type of information is currently sent. The server and client parsing data is used to determine which type of message belongs to.
public static final int CHAT_PRIVATE = 111; // Instruction for private chat public static final int CHAT_GROUP = 222; // Instruction for group chat public static final int SOCKET_SUCCESS = 333; // Instruction for successful socket connection public static final int SOCKET_FAIL = 444; // Instruction for failed socket connection public static final int CONNECT_SUCCESS = 666; // Instruction for successful socket connection public static final int CONNECT_FAIL = 777; // The command for socket connection failed public static final int LOGIN_ARG = 888; // The socket receives the command for signing the login of the new user public static final int CANCEL_ARG = 999; // The command for signing the login of the user public static final int NEW_CLIENT = 3332; // The command for signing the login of the new user public static final int ALL_CLIENT = 3432; // The command for signing the login of all online users public static final int SEND_PRIVATE = 5666; // The command for sending private chat messages public static final int SEND_IPlIST = 6666; // Instruction to send logged-in user IP collection
keyIP: IP address of client message initiator
temperatureIP: Temporary IP address. If it is a type that is a private chat type, then this IP represents the IP address of the target contact.
ServerSocket
1. Receive client connection
Socket Socketclient = server.accept();
2. Turn on the thread to receive information from the client in real time
// Get the data sent by the client in real time @Override public void run() { try { while (true) { if ((acceptLine = in.readLine()) != null) { System.out.println("<the received message is >" + acceptLine); SocketEvent event = JSON.parseObject(acceptLine, SocketEvent.class); switch (event.getType()) { case UtilFactory.CHAT_GROUP: sendMsgAvoid(event.getKeyIP(), acceptLine); break; case UtilFactory.SEND_PRIVATE: event.setType(UtilFactory.CHAT_PRIVATE); sendMsgTarget(event.getTemporaryIP(), JSON.toJSONString(event)); break; } } } } catch (Exception e) { e.printStackTrace(); } }
3. Methods to send messages to specified IPs and methods to send messages to all other IPs except for your own IPs.
// Send a message to the specified ip address private void sendMsgTarget(String targetIP, String msg) { int num = mList.size(); for (int index = 0; index < num; index++) { Socket mSocket = mList.get(index); String ip = mSocket.getInetAddress().getHostAddress(); if (ip.equals(targetIP)) { PrintWriter pout = null; try { pout = new PrintWriter( new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8")), true); pout.println(msg); // Exit method return; } catch (IOException e) { e.printStackTrace(); } } } } } // Send private void sendMsgAvoid(String avoidIP, String mSString) { int num = mList.size(); for (int index = 0; index < num; index++) { Socket mSocket = mList.get(index); String ip = mSocket.getInetAddress().getHostAddress(); if (!ip.equals(avoidIP)) { PrintWriter pout = null; try { pout = new PrintWriter( new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8")), true); pout.println(msString); } catch (IOException e) { e.printStackTrace(); } } } }The client accepts all information from the server in mainActivity, repackages according to the type, and uses Eventbus to send the information to each fragment for display.
@Subscribe(threadMode = ThreadMode.MAIN) public void privateChat(SocketEvent event) { switch (event.getType()) { case MyApplication.CHAT_PRIVATE: // Post the message to the private chat room ChatMessageBean bean = new ChatMessageBean(); bean.setMsg(event.getMsg()); bean.setName(event.getKeyIP()); bean.setType(ChatMessageBean.OTHERS_ARG); EventBus.getDefault().post(bean); break; case MyApplication.SEND_PRIVATE: sendMsg(JSON.toJSONString(event)); break; } }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.