In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today, I would like to share with you how to achieve local area network chat Mini Program Java related knowledge, detailed content, clear logic, I believe that most people are too aware of this knowledge, so share this article for your reference, I hope you have something to gain after reading this article, let's take a look at it.
Development environment:
IDEA 2018.2 integrated development tools.
Implement the function:
1. Users go online, notify and register to the server.
2. under the same local area network, all registered users can have a group chat.
3. Under the same local area network, all users can have a private chat with any registered user.
4. The user goes offline, notifies the server, and the server updates the information.
The principle of implementation:
1. The server instantiates a ServerSocket object and calls the accept method to wait for the client to connect to the server.
2. The client instantiates the Socket object and uses the constructor to establish a link with the server.
3. According to the input information of the client, the server distinguishes the function of the client request and makes the corresponding response.
Practical technology:
In order to process client requests efficiently, multithreading is used to process client requests on the server side. And use ConcurrentHashMap to store all registered clients.
Project source code (the explanation is written in the comments of the code):
Server side:
Import java.io.IOException;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;import java.util.Map;import java.util.Scanner;import java.util.Set;import java.util.concurrent.*;import java.util.regex.Matcher;import java.util.regex.Pattern;public class ManyThreadServer {/ / stores all registered clients private static Map clientMap = new ConcurrentHashMap () / / specific processing of each client's request private static class ExcuteClient implements Runnable {private Socket client; public ExcuteClient (Socket client) {this.client = client } @ Override public void run () {try {/ / gets the output stream of the client, reads the client message, and processes Scanner in = new Scanner (client.getInputStream ()); String strFromClient While (true) {if (in.hasNextLine ()) {strFromClient = in.nextLine (); / / the default line wrap under Windows is:\ r\ n, so convert\ r to the empty string Pattern pattern = Pattern.compile ("\ r") Matcher matcher = pattern.matcher (strFromClient); strFromClient = matcher.replaceAll (""); / / Registration process if (strFromClient.startsWith ("useName")) {String useName = strFromClient.split ("\\:") [1] RegisterUser (useName,client); continue;} / / Group chat feature if (strFromClient.startsWith ("G")) {String msg = strFromClient.split ("\\:") [1] GroupChat (msg,client); continue } / / Private chat function if (strFromClient.startsWith ("P")) {String userName = strFromClient.split ("\\:") [1] .split ("-") [0] String msg = strFromClient.split ("\\:") [1] .split ("-") [1]; privateChat (userName,msg,client); continue } / / user exits if (strFromClient.startsWith ("B")) {String userName = null / / find UserName for (String keyName: clientMap.keySet ()) {if (clientMap.get (keyName) .equals (client)) {userName = keyName according to Socket }} System.out.println ("user" + userName + "offline.") ; clientMap.remove (userName); System.out.println ("current shared users" + clientMap.size () + "people"); continue } else {PrintStream out = new PrintStream (client.getOutputStream (), true, "UTF-8"); out.println ("input error.") ;} catch (IOException e) {e.printStackTrace ();}} private void registerUser (String name,Socket client) {System.out.println ("user:" + name + "is online!") ; clientMap.put (name,client); System.out.println ("current online count:" + clientMap.size () + "people!") / / since the user is registering, the server informs the user of the registration result try {PrintStream out = new PrintStream (client.getOutputStream (), true, "UTF-8"); out.println ("user registered successfully!") ;} catch (IOException e) {e.printStackTrace ();}} private void groupChat (String msg,Socket client) {/ / take out all the Entry objects in the clientMap, traverse each user, and send the message Set clientSet = clientMap.entrySet () For (Map.Entry entry:clientSet) {try {Socket socket = entry.getValue (); / / get the output stream and send the message PrintStream out = new PrintStream (socket.getOutputStream (), true, "UTF-8") to the client Out.println ("group chat message from port number" + client.getPort () + ":" + msg);} catch (IOException e) {e.printStackTrace ();} private void privateChat (String userName,String msg,Socket client) {Socket privateSocket = clientMap.get (userName) Try {PrintStream out = new PrintStream (privateSocket.getOutputStream (), true, "UTF-8"); out.println ("message from port number:" + client.getPort () + ":" + msg);} catch (IOException e) {e.printStackTrace () } public static void main (String [] args) throws Exception {/ / to improve efficiency, multithreading is used to process ExecutorService executorService = Executors.newFixedThreadPool (30); / / instantiate the ServerSocket object and specify IP as the local host with a port number of 6666 ServerSocket serverSocket = new ServerSocket (6666); for (int I = 0; I < 30) ITunes +) {System.out.println ("waiting for the user to connect.") ; / wait for the client to connect to the server Socket client = serverSocket.accept (); System.out.println ("there is a client connection, the port number is" + client.getPort ()); / / start the thread and process the client request executorService.submit (new ExcuteClient (client)) } / / close the thread, close the server executorService.shutdown (); serverSocket.close ();}}
Client:
Import java.io.IOException;import java.io.PrintStream;import java.net.Socket;import java.util.Scanner; / * receives a message from the server * / class FromServer implements Runnable {Socket client; public FromServer (Socket client) {this.client = client;} @ Override public void run () {try {Scanner in = new Scanner (client.getInputStream ()) While (true) {if (in.hasNextLine ()) {System.out.println ("Server:" + in.nextLine ()) } / / determine whether the client exits, if launched, jump out of the loop, and close the stream if (client.isClosed ()) {System.out.println ("client closes.") ; break;}} in.close ();} catch (IOException e) {e.printStackTrace ();} / * send a message to the server * / class ToServer implements Runnable {Socket client; public ToServer (Socket client) {this.client = client } @ Override public void run () {try {Scanner scanner = new Scanner (System.in); PrintStream out = new PrintStream (client.getOutputStream (), true, "UTF-8"); while (true) {System.out.println ("Please enter information:"); String strToserver If (scanner.hasNextLine ()) {strToserver = scanner.nextLine () .trim (); out.println (strToserver); / / client exit flag: B if (strToserver.startsWith ("B")) {System.out.println ("client exit.") ; scanner.close (); out.close (); client.close (); break;} catch (IOException e) {e.printStackTrace () } public class ManyThreadClient {public static void main (String [] args) {try {/ / instantiate the Socket object and establish a connection with the server Socket client = new Socket ("127.0.0.1", 6666) / / in order to send and receive messages at the same time, use multithreading to process Thread thread1 = new Thread (new FromServer (client)); Thread thread2 = new Thread (new ToServer (client)); thread1.start (); thread2.start ();} catch (IOException e) {e.printStackTrace () } these are all the contents of the article "how to implement Local area Network chat Mini Program by Java". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.