您的位置:首页 > 理论基础 > 计算机网络

黑马程序员------毕老师视频笔记第23-24天------网络编程(3)

2014-06-09 04:48 435 查看
---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------

UDP应用

简易聊天软件

编写一个聊天程序

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

这两部分需要同时执行,那就需要用到多线程技术

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

因为收和发的动作不一致,所以要定义两个run方法,而且这两个方法要封装到不同的类中

import java.net.*;
import java.io.*;

class Send implements Runnable
{
private DatagramSocket ds = null;
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("000".equals(line))
break;
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10020);
ds.send(dp);
}
}
catch (Exception e)
{
throw new RuntimeException("发送失败");
}
}
}
class Rece implements Runnable
{
private DatagramSocket ds = null;
public Rece(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 e)
{
throw new RuntimeException("你的接受端挂了");
}
}
}
class Chat
{
public static void main(String [] args)throws Exception
{
DatagramSocket dsSend = new DatagramSocket();
DatagramSocket dsRece = new DatagramSocket(10020);
new Thread(new Send(dsSend)).start();
new Thread(new Rece(dsRece)).start();
}
}


运行Chat之后,在本机测试结果如下,由于是广播方式发送消息,所以一个网段的所有计算机,只要持有Send.class,Rece.class,Chat.class,然后持有jdk,运行Chat.class文件,都可以接收和发送消息。



---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: