程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 更多關於編程 >> Java基於socket實現簡易聊天室實例

Java基於socket實現簡易聊天室實例

編輯:更多關於編程

       本文實例講述了Java基於socket實現簡易聊天室的方法。分享給大家供大家參考。具體實現方法如下:

      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 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

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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程序設計有所幫助。

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved