1. 程式人生 > >用udp實現群聊

用udp實現群聊

package cn.udp;

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 ChatSender extends Thread{
@Override
public void run() {
 //建立udp服務
	DatagramSocket socket;
	try {
		socket = new DatagramSocket();
    //準備資料,把資料封裝到資料包中傳送
		//File file = new File("e:\\input.txt");
		//FileInputStream openInputStream = FileUtils.openInputStream(file);
		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.getByName("172.27.255.255"), 9091);
		    //把資料傳送出去
		    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 cn.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


//群聊接收端
public class ChatReceive extends Thread{
 
	@Override
	public void run() {
     //建立udp服務,要監聽一個埠
		try {
			DatagramSocket socket=new DatagramSocket(9091);
//準備空的資料包儲存資料
			byte[] buf=new byte[1024];
			DatagramPacket packet=new DatagramPacket(buf, buf.length);
			boolean flag=true;
			while(flag){
				socket.receive(packet);
				System.out.println(packet.getAddress().getHostName()+" "+new String(buf,0,packet.getLength()));
			}
			socket.close();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}
}

package cn.udp;

public class ChatMain {

	public static void main(String[] args) {
		ChatReceive chatrecevie=new ChatReceive();
		chatrecevie.start();
	
		ChatSender sender=new ChatSender();
		sender.start();
	
	
	}
}