Java example of simple chat room based on socket

Source: Internet
Author: User
Tags socket

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

?

, catch (Exception e) {}}}
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 ");

The Operation effect chart is as follows:

I hope this article will help you with your Java programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.