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
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16 |
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 Ioexc eption {System.out.println ("----into the chat room----"); Datagramsocket send = new Datagramsocket (); Datagramsocket rece = new Datagramsocket (10001); New Thread (new Senddemo (send)). Start ()//Initiate send the thread new thread (new Receivedemo (Rece)). Start ()//start receive the thread}} |
Senddemo.java
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The |
|
Receivedemo.java
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The |
package com.socket.demo; Import Java.net.DatagramP Acket; 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 "); |
, catch (Exception e) {}}}
The Operation effect chart is as follows:
I hope this article will help you with your Java programming.