public class chatDialog { public static void main(String[] args) throws Exception, IOException { System.out.println("聊天小程序:"); // System.out.println(InetAddress.getByName("download.filesfrog.com") // .getHostAddress()); // System.out.println(Arrays.toString("你好".getBytes()));//[-60, -29, -70, -61] // byte[] buf = {-60, -29, -70, -61}; // System.out.println(new String(buf));// 你好 // System.out.println(Arrays.toString(buf));// [-60, -29, -70, -61] // System.out.println(buf.toString());// [B@15bdc50 DatagramSocket ds = new DatagramSocket(1233); new Thread(new receive(ds)).start(); //发送到哪个IP InetAddress ia = InetAddress.getByName("yun-pc");//yun-pc localHost 127.0.0.1都是本机主机名 new Thread(new send(ia)).start(); } } class receive implements Runnable{ DatagramSocket ds ; public receive(DatagramSocket ds) { super(); this.ds = ds; } public void run() { try { while (true) { byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); ds.receive(dp); //如果有网络 接收的就是网络设置的本机IP 如果没网络就是本机IP127.0.0.1 String IP = dp.getAddress().getHostAddress(); byte[] get = dp.getData(); System.out.println(IP + ":\r\n" + new String(get)); } } catch (Exception e) { e.printStackTrace(); } } } class send implements Runnable{ InetAddress ia; private DatagramSocket s; send(InetAddress ia){ this.ia = ia; } public void run() { try { s = new DatagramSocket(); while (true) { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String line = br.readLine(); byte[] buf = line.getBytes(); DatagramPacket dp = new DatagramPacket(buf, buf.length, ia, 1233); s.send(dp); } } catch (Exception e) { e.printStackTrace(); } } }
UDP的聊天小程序
原创
©著作权归作者所有:来自51CTO博客作者倁之的原创作品,请联系作者获取转载授权,否则将追究法律责任
下一篇:字符串与 集合
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Java使用UDP协议编写聊天程序
一个窗口的聊天程序
java 多线程 聊天 网络 System -
小程序时时聊天javascript github .net