网络编程――UDP聊天窗口

UDP

编写一个聊天程序

有接收的部分,和发数据的部分

这两部分需要同时执行在一个进程中

那就需要用到多线程技术

一个线程控制接收,一个线程控制发送


因为发和收动作是不一致的,所以要定义两个run方法

而且这两个方法要封装到不同的类中

import java.io.*;
import java.net.*;
class  send implements Runnable
{
	private DatagramSocket ds;
	public send(DatagramSocket ds)
	{
		this.ds = ds;
	}
	public void run()
	{
		try
		{		
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String line = null;
			while ((line = br.readLine())!=null)//必须
			{
				if("886".equals(line))//line.equals("886")运行出错,编译正常
					break;
				byte[] buf = line.getBytes();
				DatagramPacket dp = 
					new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.255"),11000);
				ds.send(dp);
			}
			//ds.close();
		}
		catch (Exception e)
		{
			throw new RuntimeException("发送 出错");
		}
		
	}
	

}
/*接收端*/
class  rece implements Runnable
{
	private DatagramSocket ds;
	public rece(DatagramSocket ds)
	{
		this.ds = ds;
	}
	public void run()
	{
		try
		{
			while (true)//一直进行 一直等待接收
			{	
				byte[] buf = new byte[1024*14];
				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 e)
		{
			throw new RuntimeException("接收 出错");
		}
	}
}

class  chatDemo
{
	public static void main(String[] args) throws Exception
	{
		System.out.println("聊天小程序");
		DatagramSocket sendSocket = new DatagramSocket();
		DatagramSocket receSocket = new DatagramSocket(11000);
		new Thread(new send(sendSocket)).start();
		new Thread(new rece(receSocket)).start();
	}
}


你可能感兴趣的:(网络编程udp)