【小程式】使用UDP實現群聊功能

weixin_33751566發表於2016-12-24

說明:該程式使用了多執行緒技術,在使用的時候請將傳送IP該成廣播IP地址,即可實現群聊:

/*

* 群聊主執行緒

*/

package com.lin.michael;

public class CharMain {

public static void main(String[] args){

//啟動接收執行緒

ChartReceieve chartReceieve = new ChartReceieve();

chartReceieve.start();

//開啟傳送執行緒

ChartSender chartSender = new ChartSender();

chartSender.start();

}

}

//傳送類

/*

* 群聊傳送端

*/

package com.lin.michael;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

import java.net.UnknownHostException;

public class ChartSender extends Thread {

@Override

public void run() {

try {

//1.建立udp通訊

DatagramSocket socket = new DatagramSocket();

//2.準備資料,把資料放入到資料包中傳送

BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));

String line = null;

DatagramPacket packet = null;

while((line=keyReader.readLine())!=null){

//把資料封裝到資料包中傳送出去

packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getLocalHost(),9090);

//把資料傳送出去

socket.send(packet);

}

//關閉資源

socket.close();

} catch (SocketException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

//接收類

/*

* 群聊接收端

*/

package com.lin.michael;

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.SocketException;

public class ChartReceieve extends Thread{

@Override

public void run() {

try {

//1.建立udp服務,要監聽一個埠;

DatagramSocket socket = new DatagramSocket(9090);

//2.準備資料並使用包來封裝

byte[] buf = new byte[1024];

DatagramPacket packet = new DatagramPacket(buf, buf.length);

//持續接收傳送的資料

while(true){

//接收資料包放入到packet中

socket.receive(packet);

System.out.println(packet.getAddress().getHostAddress() + "說:" + new String(buf, 0, packet.getLength()));

}

} catch (SocketException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

相關文章