The example of this article tells the way Java realizes a simple chat room based on SOCKET. Share it for everyone for your reference. The specific implementation method is as follows:
Chatroomdemo.java
package com.socket.demo; Import Java.io.ioException; Import Java.net.dataGramsocket; Public Classdemo { /** * @param ARGS * WS IOEXCEPTION */ Public Static Void Main (String [] ARGS) Throws IOEXCEPTION {System.out.println ("---- enter the chat room ----"); ad to (newsdemo (send)). Start (); // Start the sender thread New Thread (New Receivedemo (Rece). Start (); // Start the receiving end thread}}}
Senddemo.java
package com.socket.demo; Import Java.io.BufferedReader; Import Java.Io.inputStreamReader; Import Java.net.DataGrampacket; Import amsocket; Import Java.net.ineTaddress; Public Class Senddemo Implements Runnable {Private DataGramsocket ds; // There is a parameter constructor Public Senddemo (DataGramsocket DS) {this.ds = ds;} @Override Public void Run () {Try {bufferedReader bufr = new burningReader (New InputStreamReader (System.in)); String line = null; While ((line = bufr.readline ())! = Null) {byte [] buf = line.getbytes (); / * * * * * * * * //192.168.1.255 is the information of the IP segment, sent to this IP information, to this IP information, to this IP information, * All IP addresses in the IP segment of 192.168.1.1-192.168.1.255 can receive messages*/ datagrampacket DP = New DataGrampacket (BUF, BUF.Length, Inetaddress.GetByName ("192.168.1. 255 "), 10001); DS .send (dp); if ("886" .equals (line) break;} ds.close ();} Catch (Exception E) {}}}}}
Receivedemo.java
package com.socket.demo; Import Java.net.dataGrampacket; Import Java.net.DataGramsocket; Public Class Receptemo Implements Runnable {PRIV ATE DataGramsocket DS; Public Receivedemo (DataGramsocket DS) {this.ds = ds;} @Override Public void Run () {Try {While (TRUE) {// 2, create a packet. byte [] buf = new byte [1024]; DataGrampacket dp = new datagrampacket (buf, buf.length); // 3, use the receiving method to store the data into the data packet. ds.receive (dp); // blocking. // 4, analyze the data through the method of the data packet object, such as, address, port, data content. String ip = dp.getaddress (). Gethostaddress (); int port = dp.getport (); system.out.println ("-------------" + port); string text = new string ( dp.getdata (), 0, dp.getlenth ()); System.out.println (ip + "::" " + Text); if (text.equals (" 886 ") {system.out.println (ip ip (ip ip + ".... Exit the chat room");}} catch (exception e) {}}}
The running renderings are as follows:
It is hoped that this article is helpful to everyone's Java program design.