Java基于socket实现简易聊天室实例


本文实例讲述了Java基于socket实现简易聊天室的方法。分享给大家供大家参考。具体实现方法如下:

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("----进入聊天室----"); 
    DatagramSocket send = new DatagramSocket(); 
    DatagramSocket rece = new DatagramSocket(10001); 
    new Thread(new SendDemo(send)).start();// 启动发送端线程 
    new Thread(new ReceiveDemo(rece)).start();// 启动接收端线程 
  } 
}

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; 
  // 有参数构造函数 
  public SendDemo(DatagramSocket ds) { 
    this.ds = ds; 
  } 
  @Override 
  public void run() { 
    try { 
      BufferedReader bufr = new BufferedReader(new InputStreamReader( 
          System.in)); 
      String line = null; 
      while ((line = bufr.readLine()) != null) { 
        byte[] buf = line.getBytes(); 
        /* 
         * //192.168.1.255是ip段广播地址,发给这个IP的信息, 
         * 在192.168.1.1-192.168.1.255的ip段的所有IP地址都能收到消息 
         */ 
        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 ReceiveDemo implements Runnable { 
  private DatagramSocket ds; 
  public ReceiveDemo(DatagramSocket ds) { 
    this.ds = ds; 
  } 
  @Override 
  public void run() { 
    try { 
      while (true) { 
        // 2,创建数据包。 
        byte[] buf = new byte[1024]; 
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        // 3,使用接收方法将数据存储到数据包中。 
        ds.receive(dp);// 阻塞式的。 
        // 4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。 
        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 + "....退出聊天室"); 
        } 
      } 
    } catch (Exception e) { 
    } 
  } 
}

运行效果图如下:

希望本文所述对大家的java程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3