------- android培训、java培训、期待与您交流! ----------
public class InetAddressTest { public static void main(String[] args) throws Exception { // 根据主机名来获取对应的InetAddress实例 InetAddress ip = InetAddress.getByName("www.baidu.com"); // 判断是否可达 System.out.println("百度:" + ip.toString() + " : "+ip.isReachable(5000)); // 获取该InetAddress实例的IP字符串 System.out.println(ip.getCanonicalHostName()); System.out.println(ip.getHostName()); System.out.println(ip.getHostAddress()); // 根据原始IP地址来获取对应的InetAddress实例 // InetAddress local = InetAddress.getByAddress(new byte[]{127,0,0,1}); InetAddress local = InetAddress.getLocalHost(); System.out.println("本机是否可达:" + local.isReachable(2000)+ " : " + local.getHostAddress()); // 获取该InetAddress实例对应的全限定域名 System.out.println(local.getCanonicalHostName()); } }运行结果是:
byte[] buf = "UDP发送端".getBytes(); DatagramPacket dpSent = new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),30000); DatagramSocket ds = new DatagramSocket(); ds.sent(dpSent); ds.close();
DatagramSocket ds = new DatagramSocket(30000);//接收端需要指定端口 byte[] buf = new byte[4*1024]; DatagramPacket dpRece = new DatagramPacket(buf,buf.length); ds.receive(dpRece); byte[] bufRece = dpRece.getData(); System.out.println(new String(bufRece));广播地址:192.168.1.255
Socket s = new Socket("192.168.1.66",9999); OutputStream out = s.getOutputStream();
ServerSocket ss = new ServerSocket(9999); Socket s = ss.accept(); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream();
String key = URLEncoder.encode("黑马Java程序员","gbk");//---%BA%DA%C2%EDJava%B3%CC%D0%F2%D4%B1 String keyWord = URLDecoder.decode("%BA%DA%C2%EDJava%B3%CC%D0%F2%D4%B1","gbk");//---黑马Java程序员
URLConnection conn = url.openConnection(); conn.setRequestProperty(key,value); conn.getInputStream(); conn.getOutputStream(); Map<String,List<String>> map = conn.getRequestProperties(); //返回一个由此连接的一般请求属性构成的不可修改的 Map。 Map<String,List<String>> map = conn.getHeaderFields(); //返回头字段的不可修改的 Map。
public class URLDemo { public static void main(String[] args) throws IOException { String str_url = "http://192.168.1.66:8080/myweb/1.html"; URL url = new URL(str_url); // System.out.println("getProtocol:"+url.getProtocol()); // System.out.println("getHost:"+url.getHost()); // System.out.println("getPort:"+url.getPort()); // System.out.println("getFile:"+url.getFile()); // System.out.println("getPath:"+url.getPath()); // System.out.println("getQuery:"+url.getQuery()); // InputStream in = url.openStream(); //获取url对象的Url连接器对象。 URLConnection conn = url.openConnection(); // String value = conn.getHeaderField("Content-Type"); // System.out.println(value); // System.out.println(conn); //输出sun.net.www.protocol.http.HttpURLConnection:http://192.168.1.100:8080/myweb/1.html InputStream in = conn.getInputStream(); byte[] buf = new byte[1024]; int len = in.read(buf); String text = new String(buf,0,len); System.out.println(text); in.close(); } }
------- android培训、java培训、期待与您交流! ----------