Java网络编程—UDP协议多线程聊天室

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

发送端:

public class SenderThread implements Runnable{

	//创建发送端Socket对象
	private DatagramSocket ds;
	
	public SenderThread(DatagramSocket ds){
		this.ds = ds;
	}

	@Override
	public void run() {
		try{
				//封装键盘录入数据
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
				String line = null;
				
				while((line = br.readLine()) != null){
					
					//终止循环
					if(line.equals("end")){
						break;
					}
					//创建数据,打包数据。 主机名:boost  端口号:2020
					byte[] bt = line.getBytes();
					DatagramPacket dp = new DatagramPacket(bt, bt.length,
							InetAddress.getByName("Boost"), 2020);
					
					//发送数据
					ds.send(dp);
				}

				//关闭ds对象,同时释放内存
				ds.close();
				
		}catch(IOException e){
			e.printStackTrace();
		}
		
	}
}

接收端:

public class ReceiveThread implements Runnable{

	//创建接收端Socket对象
	private DatagramSocket ds;
	
	public ReceiveThread(DatagramSocket ds){
		this.ds = ds;
	}

	@Override
	public void run() {
		
		try{
			while(true){
				
				//创建一个空的数据包
				byte[] bt = new byte[1024];	
				DatagramPacket dp = new DatagramPacket(bt, bt.length);

				//接收数据
				ds.receive(dp);

				//解析数据
				String ip = dp.getAddress().getHostAddress();
				String data = new String(dp.getData(),0,dp.getLength());
				System.out.println("来自" + ip + "的信息:"+data);
			}
		}catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}

多线程部分:

public class ChatRoom {

	public static void main(String[] args) throws IOException {

		//创建发送端Socket对象
		DatagramSocket dsSend = new DatagramSocket();
		//创建接收端Socket对象
		DatagramSocket dsRec = new DatagramSocket(2020);
		
		//创建发送端线程
		SenderThread st = new SenderThread(dsSend);
		//创建接收端线程
		ReceiveThread rt = new ReceiveThread(dsRec);
		
		Thread t1 = new Thread(st);
		Thread t2 = new Thread(rt);

		//执行线程		
		t1.start();
		t2.start();
	}	
}

 

转载于:https://my.oschina.net/drathin/blog/1925983

你可能感兴趣的:(Java网络编程—UDP协议多线程聊天室)