1 Url UrlConnection
public static void main(String[] args) throws Exception { URL url=new URL("Http://www.baidu.com"); URLConnection connection=url.openConnection(); InputStream iStream =connection.getInputStream(); OutputStream outputStream=new FileOutputStream("D:/baidu.html"); int length=0; byte [] buffer=new byte[1024]; while(length!=-1) { length=iStream.read(buffer,0,buffer.length); outputStream.write(buffer); } outputStream.close(); iStream.close(); }2 InetAddress
InetAddress address=InetAddress.getLocalHost(); System.out.println(address); address=InetAddress.getByName("WWW.baidu.com"); System.out.println(address); }
Socket是连接运行在网络上的两个程序间的双向通讯的端点
1) 建立Socket连接
2) 获得输入/输出流
3)读/写数据
4) 关闭输入/输出流
5) 关闭Socket
ServerSocket serverSocket=new ServerSocket(50116); Socket listnerSocket=serverSocket.accept(); System.out.println("服务器消息:有人连接了"); InputStream inputStream=listnerSocket.getInputStream(); byte []buffer=new byte[1024]; inputStream.read(buffer); System.out.println("客户端消息:"+new String(buffer)); OutputStream outputStream=listnerSocket.getOutputStream(); outputStream.write("Welcome".getBytes()); outputStream.close(); inputStream.close(); listnerSocket.close();
Socket socket=new Socket("127.0.0.1",50116); OutputStream outputStream=socket.getOutputStream(); outputStream.write("hello".getBytes()); InputStream inputStream=socket.getInputStream(); byte [] reader=new byte[1024]; inputStream.read(reader); System.out.println("服务器消息:"+new String(reader)); outputStream.close(); inputStream.close(); socket.close();
4 UDP
DatagramSocket socket=new DatagramSocket(); byte[] data="bingjia i miss you".getBytes(); DatagramPacket packet=new DatagramPacket(data, data.length, InetAddress.getByName("127.0.0.1"),50116); socket.send(packet); byte [] dataReceiver=new byte[10000]; DatagramPacket packetReceive=new DatagramPacket(dataReceiver,10000); socket.receive(packetReceive); System.out.println(new String(dataReceiver,0,packetReceive.getLength())+" Port"+packetReceive.getPort());
DatagramSocket socket=new DatagramSocket(50116); byte [] dataReceiver=new byte[10000]; DatagramPacket packetReceive=new DatagramPacket(dataReceiver,10000); socket.receive(packetReceive); System.out.println(new String(dataReceiver,0,packetReceive.getLength())+" Port"+packetReceive.getPort()); byte[] data="hehe".getBytes(); DatagramPacket packet=new DatagramPacket(data, data.length, packetReceive.getAddress(),packetReceive.getPort()); socket.send(packet);