This article describes the Java based on the socket implementation of simple chat room method. Share to everyone for your reference. The implementation methods are as follows:
Chatroomdemo.java
Package Com.socket.demo;
Import java.io.IOException;
Import Java.net.DatagramSocket;
public class Chatroomdemo {
/**
* @param args
* @throws ioexception
/public static void main ( String[] args) throws IOException {
System.out.println ("----Enter chat room----");
Datagramsocket send = new Datagramsocket ();
Datagramsocket rece = new Datagramsocket (10001);
New Thread (new Senddemo (send)). Start ()//starts sending the thread
new thread (new Receivedemo (Rece)). Start ()//start receive thread
}
Senddemo.java
Package Com.socket.demo;
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
public class Senddemo implements Runnable {private Datagramsocket ds;
There are parameter constructors public Senddemo (Datagramsocket ds) {this.ds = ds;
@Override public void Run () {try {BufferedReader bufr = new BufferedReader (
system.in));
String line = null;
while (line = Bufr.readline ())!= null) {byte[] buf = Line.getbytes ();
* *//192.168.1.255 is the IP segment broadcast address, send this IP information, * in 192.168.1.1-192.168.1.255 IP segment of all IP address can receive message * *
Datagrampacket DP = new Datagrampacket (buf, Buf.length,inetaddress.getbyname ("192.168.1.255"), 10001);
Ds.send (DP);
if ("886". equals) break;
} ds.close ();
The catch (Exception e) {}}}
Receivedemo.java
package Com.socket.demo;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
public class Receivedemo implements Runnable {private Datagramsocket ds;
Public Receivedemo (Datagramsocket ds) {this.ds = ds;
Create a packet @Override public void run () {try {(true) {//2).
byte[] buf = new byte[1024];
Datagrampacket DP = new Datagrampacket (buf, buf.length);
3, use the Receive method to store the data in the packet.
Ds.receive (DP);//blocking type.
4, through the method of the packet object, parse the data, such as address, port, data content.
String IP = dp.getaddress (). gethostaddress ();
int port = Dp.getport ();
SYSTEM.OUT.PRINTLN ("----Port-----" + port);
String text = new String (Dp.getdata (), 0, Dp.getlength ());
SYSTEM.OUT.PRINTLN (IP + "::" + text); if (Text.equals ("886")) {System.out.println (IP +) ....
Exit chat room ");
for catch (Exception e) {}}}
The Operation effect chart is as follows:
I hope this article will help you with your Java programming.