简单dos聊天工具,dos聊天工具,// 因为发送和接收是同
分享于 点击 31853 次 点评:237
简单dos聊天工具,dos聊天工具,// 因为发送和接收是同
// 因为发送和接收是同时的所以要用多线程// 导包 import java.net.*;import java.io.*;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) { if("88".equals(line)) break; //当输入为 88时 停止 读入 byte [] buf=line.getBytes(); DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.3.255"),10000); // 向指定主机(IP) 发送消息 如果主机ip为192.168.3.255 则表示 局域网中群聊 1234为端口号 注意不要与程序端口号重名 ds.send(dp); } } catch (Exception e) { throw new RuntimeException("发送端失败!"); } }}class Receive implements Runnable{ private DatagramSocket ds; public Receive(DatagramSocket ds) { this.ds=ds; } public void run() { try { while(true) { byte bfr[]=new byte[1024]; DatagramPacket dp=new DatagramPacket(bfr,bfr.length); ds.receive(dp); //通过接收的数据包 获取发送端的 主机IP 和 数据 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("接收端失败!"); } }}public class DOS_liaotian{ public static void main(String args[]) throws Exception { DatagramSocket sendSocket=new DatagramSocket(); DatagramSocket receiveSocket=new DatagramSocket(10001); // 注意 发送端可以不要端口号 但接收端 必须要端口号 且与前面的端口号一致 new Thread(new Send(sendSocket)).start(); new Thread(new Receive(receiveSocket)).start(); }}//该片段来自于http://byrx.net
用户点评