1.URL
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter;import java.net.URL;
public class Test_URL {
public static void main(String[] args) throws IOException, InterruptedException { URL url = new URL(""); System.out.println("URL:"+url.toString()+"\n" +"协议:"+url.getProtocol()+"\n" +"域名:"+url.getHost()+"\n" +"端口:"+(url.getPort()==-1? 80:url.getPort())+"\n" +"资源:"+url.getFile()+"\n" +"锚点:"+url.getRef()+"\n" +"参数:"+url.getQuery()+"\n" //若锚点存在,则返回null +"相对路径:"+url.getPath()); Thread.sleep(3000); BufferedReader br =new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("test/www.html"), "UTF-8")); String msg = null; while(null!=(msg=br.readLine())){ System.out.println(msg); bw.append(msg); bw.newLine(); } bw.flush(); bw.close(); br.close(); } } 2.UDPimport java.io.IOException;
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress;public class Test_UDP {
public static class Server implements Runnable { public void run() { try { DatagramSocket server; server = new DatagramSocket(3333); byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container, container.length); server.receive(packet); byte[] data = packet.getData(); int len = packet.getLength(); System.out.println("服务器已接受信息"); Thread.sleep(800); System.out.println("信息:"+new String(data, 0, len)); server.close(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }}public static class Client implements Runnable { public void run() { try { DatagramSocket client = new DatagramSocket(5555); String msg = "udp测试成功!"; byte[] data = msg.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, new InetSocketAddress("myLaptop", 3333)); client.send(packet); client.close(); } catch (IOException e) { e.printStackTrace(); } }}public static void main(String[] args) throws IOException, InterruptedException { new Thread(new Server()).start(); System.out.println("服务器接收就绪"); Thread.sleep(1600); System.out.print("客户端正在发送信息"); for(int i=0; i<3; i++){ Thread.sleep(400); System.out.print("."); } System.out.println(); Thread.sleep(1200); new Thread(new Client()).start();}
}