udp通信

本文介绍了一个基于UDP协议的群聊系统的实现过程。系统通过创建发送端和接收端的DatagramSocket来完成消息的发送与接收,并利用多线程技术实现了发送与接收的并发执行。用户可以通过控制台输入消息进行发送,同时也能接收到其他用户的消息。

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

public class QL {

	
	public static void main(String[] args) throws SocketException {
		/*
		 * 1。需求:通过UDP实现群聊的功能;
		 * 思路:
		 * 这个程序中既有收又有发送的功能;需要同时执行,需要使用到多线程;
		 * 一个线程负责发,一个线程负责收;两个任务同时执行;
		 */
     //发送端的socket 与接收端的socket
		DatagramSocket sendScoket=new DatagramSocket();
		DatagramSocket reciveScoket=new DatagramSocket(10001);
	// 创建任务对象
		Send send=new Send(sendScoket);
		Recive recive=new Recive(reciveScoket);
	//创建线程对象
		Thread t1=new Thread(send);
		Thread t2=new Thread(recive);
		t1.start();
		t2.start();
		
	}

}

// 发送端
class Send implements Runnable{
	
    private DatagramSocket ds;
	Send(DatagramSocket ds) {
		super();
		this.ds = ds;
	}
	@Override
	public void run() {
		
		BufferedReader bufer=new BufferedReader(new InputStreamReader(System.in));
		String line =null;
		try{
		    while((line=bufer.readLine())!=null)
		     {
			byte buf[]=line.getBytes();//将数据转成字节数组;
			//将字节数据封装到数据包中
			DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("122.206.79.124"),10001);
                       //DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("122.206.79.255"),10001);
		       //3.使用Socket的数据发送方法send,把数据包发送出去;
			ds.send(dp);
            if("886".equals(line))
		      {
			     break;
		       }
			
		     }
		   } catch(IOException e){}
		
	}
	
}
//接收端
class Recive implements Runnable{
	private DatagramSocket ds;

	Recive(DatagramSocket ds) {
		super();
		this.ds = ds;
	}
	@Override
	public void run() {
	try{
		while (true)
		{
		byte buf[]=new byte[1024];
		DatagramPacket dp= new DatagramPacket(buf, buf.length);
		ds.receive(dp);     //受阻;
	
		// 通过数据包对象获取发送端的信息;包括:发送端的IP,端口,发送过来的数据;
		String ip= dp.getAddress().getHostAddress();
		int port=dp.getPort();
	
		//byte text[]=dp.getData();
		String text =new String(dp.getData(),0,dp.getLength());
		System.out.println(ip+"  "+port+":"+text);
		if(text.equals("886"))
		{
			System.out.println(ip+"离开聊天室");
			break;
		}
		}
	} catch (IOException e){}
	 }
	

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值