用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();
	
	
	}
}



你可能感兴趣的:(java基础)