Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize online chat Room with java

Shulou Source: shulou.com Published: 2022-06-02 11:37:31 09月18日 Update

Editor to share with you how to achieve java online chat room, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Online chat room

Server:

Public class Chat {public static void main (String [] args) throws IOException {System.out.println ("server starting..."); / / create server ServerSocket server=new ServerSocket (9999); / / blocking wait connection, open while (true) {Socket client=server.accept (); System.out.println ("A client has established a connection") after the client Socket has been created. New Thread (()-> {DataInputStream dis = null; DataOutputStream dos = null; try {dis = new DataInputStream (client.getInputStream ()); dos = new DataOutputStream (client.getOutputStream ());} catch (IOException E1) {e1.printStackTrace ();} boolean flag=true; while (flag) {String msg = null Try {msg = dis.readUTF (); dos.writeUTF (msg); dos.flush ();} catch (IOException e) {/ / when the client is disconnected, there is no need to loop to read the data flag=false } / / return message} try {if (nullroomroomdos) {dos.close ();}} catch (IOException e) {e.printStackTrace ();} try {if (nullroomroomdos) {dis.close () }} catch (IOException e) {e.printStackTrace ();} try {if (null filling client) {client.close ();}} catch (IOException e) {e.printStackTrace ();}}) .start ();}

Client:

Public class Client {

Public static void main (String [] args) throws UnknownHostException, IOException {System.out.println ("client launching..."); Socket client=new Socket ("localhost", 9999); / / client sending message BufferedReader br=new BufferedReader (new InputStreamReader (System.in)); DataOutputStream dos=new DataOutputStream (client.getOutputStream ()); DataInputStream dis = new DataInputStream (client.getInputStream ()); boolean flag=true; while (flag) {System.out.println ("Please enter message") String msg=br.readLine (); dos.writeUTF (msg); dos.flush (); / / get the message msg=dis.readUTF (); System.out.println (msg);} dos.close (); dis.close (); client.close ();}} these are all the contents of the article "how to implement an online chat room in java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Customers clients messages chat rooms online servers articles services content not much not much most data more knowledge industry information information channels channels set up Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Linux OPPO Reno MariaDB NVidia