黑马程序员 java之DOS 聊天

                 ----------- android培训java培训、java学习型技术博客、期待与您交流! ------------

1,在一个局域网内通过192.168.1.255来实现局域网的聊天。

2,利用多线程来控制信息的发送和接受。

3,利用udp的特点来实现DatagramSocket的服务。

import java.io.*;
import java.net.*;
class  DatagramSocketTest
{
	public static void main(String[] args)throws Exception
	{
		DatagramSocket send = new DatagramSocket();
		DatagramSocket receive = new DatagramSocket(8888);
		new Thread(new SendClient(send)).start();
		new Thread(new ReceiveClient(receive)).start();
	}
}
class SendClient implements Runnable
{
	private DatagramSocket dgs;
	SendClient(DatagramSocket dgs)
	{
		this.dgs = dgs;
	}
	public void run()
	{
		BufferedReader bfr = null;
			try
			{
				bfr = new BufferedReader(new InputStreamReader(System.in));
				String st = null;
				while ((st = bfr.readLine())!= null)
				{
					if("886".equals(st))
						break;
					byte[] buf = st.getBytes();
					DatagramPacket agp = 
						new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.100"),8888);
					dgs.send(agp);
				}
				dgs.close();
			}
			catch (Exception e)
			{
				throw new RuntimeException("发送失败");
			}
			finally
			{
				try
				{
					if(bfr != null)
					bfr.close();
				}
				catch (IOException e)
				{
					throw new RuntimeException("关闭流失败");
				}
			}
	}
}
class ReceiveClient implements Runnable
{
	private DatagramSocket dgs;
	ReceiveClient(DatagramSocket dgs)
	{
		this.dgs = dgs;
	}
	public void run()
	{
		try
		{
			while (true)
			{
				byte[] buf = new byte[1024];
				DatagramPacket agp = new DatagramPacket(buf,buf.length);
				dgs.receive(agp);
				String ip = agp.getAddress().getHostAddress();
				String data = new String(agp.getData(),0,agp.getLength());
				System.out.println("ip:" + ip + "--" + data); 
			}
		}
		catch (Exception e)
		{
			throw new RuntimeException("获取失败");
		}	
		
	}	
}


                  -----------  android培训 java培训 、java学习型技术博客、期待与您交流! ------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值