基于Udp的聊天室(DatagramSocket和DatagramPacket两个类)

来源:互联网 发布:淘宝注册页面在哪 编辑:程序博客网 时间:2024/06/06 03:00
import java.io.*;import java.net.*;import java.lang.*;public class Chat{public static void main(String []args) throws Exception{DatagramSocket Sendds=new DatagramSocket();DatagramSocket Receds=new DatagramSocket(10007);new Thread(new Send(Sendds)).start();new Thread(new Receive(Receds)).start();}}class Send implements Runnable//发送类{private DatagramSocket ds;public Send(DatagramSocket ds){this.ds=ds;}public void run(){try{boolean flag=true;while(flag){BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String s="";while((s=br.readLine())!=null){DatagramPacket dp=null;if(s.equals("over")){dp=new DatagramPacket(s.getBytes(),s.getBytes().length,InetAddress.getByName("127.0.0.1"),10006);//在数据报包中指定具体的向那个主机的那个端口发,当然一字节的形式flag=false;ds.send(dp);break;}else{dp=new DatagramPacket(s.getBytes(),s.getBytes().length,InetAddress.getByName("127.0.0.1"),10006);ds.send(dp);System.out.println("你说:"+s);flag=true;}}if(flag==false){System.out.println(flag);break;}}}catch(Exception e){System.out.println("发送数据异常。。。");}ds.close();}}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*64];DatagramPacket dp=new DatagramPacket(buf,buf.length);ds.receive(dp);System.out.println("hah ");String ip=dp.getAddress().getHostAddress();String data=new String (buf,0,dp.getLength());if(data.equals("over")){data="我结束了本次对话。。。拜拜";System.out.println("ip地址为:"+ip+"   他说:"+data);break;}System.out.println("ip地址为:"+ip+"   他说:"+data);}}catch(Exception e){System.out.println("接收数据异常。。。。");}}}


我写的是127,0,0,1访问的是自己电脑,也可以换ip,同样被访问的主机也应该  运行此程序,,但是要改一个不冲突的  端口。。。  即可在doc环境下实现多人聊天(多线程实现)。底下是程序运行截图。。。



原创粉丝点击