您的位置:首页 > 职场人生

黑马程序员 用UDP协议在dos命令行里模拟一个聊天程序

2013-07-04 08:51 423 查看
---------------------- android培训java培训、期待与您交流! --------------------

/*
需求: 在dos命令行里模拟一个聊天程序
有收数据的部分,和发数据的部分,这两部分需要同时执行。
那就需要用到多线程技术。
一个线程控制收,一个线程控制发。
*/
import java.io.*;
import java.net.*;
class  ChatDemo
{
public static void main(String[] args) throws Exception
{
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receSocket = new DatagramSocket(10011);//接收端要定义好所监听的端口,因为发送端设置的发送目的就是这个端口

new Thread(new Send(sendSocket)).start();//开启两个线程
new Thread(new Rece(receSocket)).start();
}
}
class Send implements Runnable//发送端
{
private DatagramSocket ds;
public Send(DatagramSocket ds)
{
this.ds = ds;
}
public void run()
{
try
{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line=bufr.readLine())!=null)//读取键盘录入的字符串
{
byte[] buf = line.getBytes();//把这字符串转成字节数组
DatagramPacket dp = /*定义数据报包,含字节数组与目的地ip是广播地址192.168.0.255,让此段网络都能收到,端口是10011*/
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.255"),10011);
ds.send(dp);//发送数据报包
if("886".equals(line))//停止发送线程
break;
}
}
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];//定义好字节数组,用来装接收的数据
DatagramPacket dp = new DatagramPacket(buf,buf.length);//接收的数据放在这个数据报包中的数组里
ds.receive(dp);
String ip = dp.getAddress()/*取出此包的IntAdress对象*/.getHostAddress();//取出ip地址

String data = new String(dp.getData(),0,dp.getLength());//取出此包中的字节数组,并转成字符串
if("886".equals(data))//当接收到的字符串是886时就停止此线程
{
System.out.println(ip+"....离开聊天室");
break;
}
System.out.println(ip+"说:"+data);//普通数据都把ip和说的内容打出来
}
}
catch (Exception e)
{
throw new RuntimeException("接收端失败");
}
}
}


----------------------
ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐