Udp实现聊天

/*
编写一个聊天程序。
有两部分,发送和接收,这两部分需要同时进行,就需要用到多线程技术。
一个线程控制发送,一个控制接收。
因为接收和发送时不同的动作,所以需要两个run方法,定义在两个类中。
*/
import java.net.*;
import java.io.*;
import java.lang.Exception;
class  Send implements Runnable
{
	private DatagramSocket ds;
	public Send(DatagramSocket ds)
	{
		this.ds = ds;
	}

	public void run()
	{
		try
		{
			BufferedReader buffr = new BufferedReader(new InputStreamReader(System.in));
			String line = null;
			while((line = buffr.readLine()) != null)
			{
				if("886".equals(line))
					break;
				byte [] buff = line.getBytes();
				DatagramPacket dp = new DatagramPacket(buff,0,buff.length,InetAddress.getByName("122.88.30.178"),10001);
				ds.send(dp);
			}
			ds.close();
		}
		catch (Exception ex)
		{
			throw new RuntimeException("发送端失败。");
		}
	}
}

class Receive implements Runnable
{
	private DatagramSocket ds;
	public Receive(DatagramSocket ds)
	{
		this.ds = ds;
	}

	public void run()
	{
		try
		{
			while(true)
			{
				byte [] buf =new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf,buf.length);
				ds.receive(dp);
				String ip = dp.getAddress().getHostAddress();
				String data = new String(dp.getData(),0,dp.getLength());
				System.out.println(ip + ".." + data);
			}
		}
		catch (Exception ex)
		{
			throw new RuntimeException("接收端失败。");
		}

	}
}

class ChatDemo
{
	public static void main(String [] args) throws Exception
	{
		DatagramSocket dsSend = new DatagramSocket();
		DatagramSocket dsReceive = new DatagramSocket(10001);
		new Thread(new Send(dsSend)).start();
		new Thread(new Receive(dsReceive)).start();

	}
}

原文地址:https://www.cnblogs.com/dengshiwei/p/4258423.html