Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Local area Network to realize the function of chat Room in Java

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the Java how to use the local area network to achieve chat room function related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this Java how to use the local area network to achieve chat room function article will have a harvest, let's take a look.

Classes and interfaces

Server class (server side)

Package Test;import java.io.IOException;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;public class Server {private static final int SERVER_PORT=30000; / / uses the CrazyitMap object to save the correspondence between each customer name and the corresponding output stream public static CrazyitMap clients=new CrazyitMap () Public void init () {try (/ / establish a listening ServerSocket ServerSocket ss=new ServerSocket (SERVER_PORT)) {/ / use an endless loop to continuously receive requests from the client while (true) {Socket socket=ss.accept (); new ServerThread (socket) .start () }} / / if an exception is thrown catch (IOException ex) {System.out.println ("server startup failed, whether the port" + SERVER_PORT+ "is occupied");}} public static void main (String [] args) {Server server=new Server (); server.init ();}}

ServerThread class

Package Test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.Socket;public class ServerThread extends Thread {private Socket socket; BufferedReader br = null; PrintStream ps = null; / / defines a constructor that receives a Socket to create the ServerThread thread public ServerThread (Socket socket) {this.socket = socket } public void run () {try {/ / get the input stream br = new BufferedReader (new InputStreamReader (socket.getInputStream () corresponding to the Socket; / / get the output stream corresponding to the Socket ps = new PrintStream (socket.getOutputStream ()); String line = null While ((line = br.readLine ())! = null) {/ / if the read line starts with CrazyitProtocol.user _ ROUND And end with it / / then you can be sure to read the user name if (line.startsWith (CrazyitProtocol.USER_ROUND) & & line.endsWith (CrazyitProtocol.USER_ROUND)) {/ / get the real message String userName = getRealMsg (line) / / if the user name repeats if (Server.clients.map.containsKey (userName)) {System.out.println ("repeat"); ps.println (CrazyitProtocol.NAME_REP);} else {System.out.println ("success") Ps.println (CrazyitProtocol.LOGIN_SUCCESS); Server.clients.put (userName, ps) }} / / if the line you read starts with CrazyitProtocol.private _ ROUND, / / you can confirm that it is a private chat. Private chat messages only send else if (line.startsWith (CrazyitProtocol.PRIVATE_ROUND) & & line.endsWith (CrazyitProtocol.PRIVATE_ROUND)) {/ / to get the real message String userAndMsg = getRealMsg (line) to a specific input stream. / / split the string with SPLIT_SIGN, the first half is private chat users, and the second half is chat message String user = userAndMsg.split (CrazyitProtocol.SPLIT_SIGN) [0]; String msg = userAndMsg.split (CrazyitProtocol.SPLIT_SIGN) [1] / / get the output stream corresponding to the private chat user, and send the private chat message Server.clients.map.get (user) .println (Server.clients.getKeyByValue (ps) + "whisper to you" + msg) } / / Public chat needs to send else {/ / get the real message String msg = getRealMsg (line) to each Socket / / traverse each output stream for (PrintStream clientPs: Server.clients.valueSet ()) {clientPs.println (Server.clients.getKeyByValue (ps) + "say:" + msg) in clients } / / after catching the exception, it indicates that there has been a problem with the client corresponding to the Socket / / so the program deletes the corresponding output stream from the Map catch (IOException e) {Server.clients.removeByValue (ps) System.out.println (Server.clients.map.size ()); / / shut down the network, IO resource try {if (br! = null) {br.close ();} if (ps! = null) {ps.close () } if (socket! = null) {socket.close ();}} catch (IOException ex) {ex.printStackTrace () } / / remove the pre-and post-protocol characters and restore them to real data private String getRealMsg (String line) {return line.substring (CrazyitProtocol.PROTOCOL_LEN,line.length ()-CrazyitProtocol.PROTOCOL_LEN);}}

Client class

Package Test;import javax.swing.*;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.Socket;import java.net.UnknownHostException;public class Client {private static final int SERVER_PORT=30000; private Socket socket; private PrintStream ps; private BufferedReader brServer; private BufferedReader keyIn Public void init () {try {/ / initializes the input stream keyIn=new BufferedReader (new InputStreamReader (System.in)) that represents the keyboard; / / connects to the server-side socket=new Socket ("127.0.0.1", SERVER_PORT); / / gets the input stream and output stream ps=new PrintStream (socket.getOutputStream ()) corresponding to the Socket BrServer=new BufferedReader (new InputStreamReader (socket.getInputStream (); String tip= ""; / / require a user name while (true) {String userName= JOptionPane.showInputDialog (tip+ "enter user name") by constantly cycling the dialog box / / send ps.println (CrazyitProtocol.USER_ROUND+userName+CrazyitProtocol.USER_ROUND) after adding the protocol string to the user name entered by the user; / / read the server response String result=brServer.readLine () / / if the username is duplicated, start the next loop if (result.equals (CrazyitProtocol.NAME_REP)) {tip= "duplicate username, please try again"; continue } / / successful server login if (result.equals (CrazyitProtocol.LOGIN_SUCCESS)) {break } / / catch an exception, close the network resource, and exit the program catch (UnknownHostException ex) {System.out.println ("cannot find the remote server, please make sure the server has started"); closeRs (); System.exit (1) } catch (IOException ex) {System.out.println ("Network exception, please log in again"); closeRs (); System.exit (1);} / / start the clientthread new ClientThread (brServer) .start () with the input stream corresponding to the Socket } / / define a read keyboard output and use the network sending method private void readAndSend () {try {/ / constantly read the keyboard input String line=null While ((line=keyIn.readLine ())! = null) {/ / if the signal sent has a colon and starts with / /, you think you want to send a private chat message if (line.indexOf (":") > 0&&line.startsWith ("/ /")) {line=line.substring (2) Ps.println (CrazyitProtocol.PRIVATE_ROUND+line.split (":") [0] + CrazyitProtocol.SPLIT_SIGN+line.split (":") [1] + CrazyitProtocol.PRIVATE_ROUND);} else {ps.println (CrazyitProtocol.MSG_ROUND+line+CrazyitProtocol.MSG_ROUND) } catch (IOException ex) {System.out.println ("abnormal network communication! Please log in again "); closeRs (); System.exit (1);}} / / close Socket, input stream, output stream method private void closeRs () {try {if (keyInstitutional null) {ps.close () } if (brserverware null) {ps.close ();} if (psicified null) {ps.close ();} if (socketpacking null) {keyIn.close () } catch (IOException ex) {ex.printStackTrace ();}} public static void main (String [] args) {Client client=new Client (); client.init (); client.readAndSend ();}}

ClientThread class

Package Test;import java.io.BufferedReader;import java.io.IOException;public class ClientThread extends Thread {/ / the client thread is responsible for processing the input stream BufferedReader br=null; / / using a network input stream to create the client thread public ClientThread (BufferedReader br) {this.br=br;} public void run () {try {String line=null / / continuously read data from the input stream and print it out to while ((line=br.readLine ())! = null) {System.out.println (line);}} catch (IOException ex) {ex.printStackTrace () } finally {try {if (brushing null) {br.close ();}} catch (IOException ex) {ex.printStackTrace ();}

CrazyitMap class

Package Test;import java.util.*;public class CrazyitMap {/ / create a thread-safe HashMap public Map map= Collections.synchronizedMap (new HashMap ()); / / delete the specified item public synchronized void removeByValue (Object value) {for (Object key:map.keySet ()) {if (map.get (key) = = value) {map.remove (key); break according to value } / / get Set collection composed of all value public synchronized Set valueSet () {Set result=new HashSet (); / / add all value in map to result collection map.forEach ((key,value)-> result.add (value)); return result } / / find key public synchronized k getKeyByValue according to value (v value) {/ / traverse the collection of all key for (k key:map.keySet ()) {/ / if the value corresponding to the specified key is the same as the searched value, the corresponding key if (map.get (key) = = value | | map.get (key) .equals (value)) {return key is returned. }} return null } / / implement the put () method This method does not allow value to repeat public synchronized v put (k key) V value) {/ / traverses the collection of all value for (v val:valueSet ()) {/ / if a value is the same as the value trying to put into the collection / / throws a RuntimeException exception if (val.equals (value) & & val.hashCode () = = value.hashCode ()) {throw new RuntimeException ("duplicate value is not allowed in MyMap instances") Return map.put (key,value);}}

CrazyitProtocol class

Package Test;public interface CrazyitProtocol {/ / defines the length of the protocol string int PROTOCOL_LEN=2; / / below are some protocol strings. The information exchanged between the server and the client should be preceded by this special string String MSG_ROUND= "θ"; String USER_ROUND= "∏∑"; String LOGIN_SUCCESS= "1"; String NAME_REP= "- 1"; String PRIVATE_ROUND= "★ [" String SPLIT_SIGN= "clients";}

Running result:

Open the server and run the three client usernames xuwei,jiji and yaou

First, send a public message:

Xuwei sent a message.

Jiji received:

Yaou received:

Send another private chat message to jiji

Xuwei sent a whisper:

Jiji received:

Yaou did not receive:

This is the end of the article on "how to use Java to achieve chat room function in local area network". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to use the local area network to achieve chat room function in Java". If you want to learn more knowledge, you are welcome to follow 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report