InetAddress提供公共的构造器,提供了几个公共的静态方法获得InetAddress对象
InetAddress localhost = InetAddress.getLocalHost();
byte[] addr = {(byte) 192,(byte) 168,88,1};
InetAddress byAddress = InetAddress.getByAddress(addr);
InetAddress byName = InetAddress.getByName("LAPTOP-3PKRMNI5");
InetAddress提供的常用方法:
InetAddress localhost = InetAddress.getLocalHost();
String hostName = localhost.getHostName();
String hostAddress = localhost.getHostAddress();
System.out.println(hostName);
System.out.println(hostAddress);
URI:表示一个统一资源标识符引用,用来唯一表示一个资源
URL:统一资源定位符,是指向互联网资源的指针,URL不仅能表示一个资源,还指明了如何locate这个资源。
url组成:
<传输协议>://<主机名>:<端口号>/<文件名>#片段名
<传输协议>://<主机名>:<端口号>/<文件名>?参数列表
@Test
public void test3() throws Exception{
URL url = new URL("www.baidu.com/");
//public URL(URL context, String spec):
url = new URL(url, "download.html");//通过一个基准url和spec拼接部分的url进行组合一块
//public URL(String protocol, String host, String file);
url = new URL("http","baidu","download.html");//三部分进行拼接
//public URL(String protocol, String host, int port, String file);
url = new URL("http", "baidu", 8080, "download.hml");
}
@Test
public void test3() throws Exception{
URL url = new URL("http://192.168.34.53:80/web1/index.html");
System.out.println("协议:"+url.getProtocol());
System.out.println("主机名:"+url.getHost());
System.out.println("端口号:"+url.getPort());//获取端口号
System.out.println("路径名:"+url.getPath());//路径名
System.out.println("文件名:"+url.getFile());
System.out.println("锚点"+url.getRef());//锚点
System.out.println("查询名:"+url.getQuery());//查询名
}
//从百度读取首页资源
@Test
public void test4() throws IOException{
URL url = new URL("http://www.baidu.com/index.html");
/*html标签(格式化数据)、css:皮肤(美化数据)、js:互动(交互数据)、数据:*/
InputStream input = url.openStream();
byte[] data = new byte[1024];
int len;
while((len=input.read(data))!=-1){
System.out.println(new String(data,0,len,"UTF-8"));
}
input.close();
}
url的openStream()可以从网上读取数据,但是无法上传数据,给服务器发送数据,如果希望,可使用URLConnection
步骤
@Test
public void test5() throws Exception{
URL url = new URL("http://www.baidu.com/index.html");
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
uc.getOutputStream().write("username=admin&password=123".getBytes());;
uc.connect();
InputStream is = uc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String string;
while((string = br.readLine())!=null){
System.out.println(string);
}
br.close();
}
分类:
TCP(Transmission Control Protocol,传输控制协议)被称为一种端对端协议,是一种面向连接的,可靠的,基于字节流的传输层的通信协议,可以连续传输大量的数据
步骤
服务器程序的工作过程包含以下五个基本的步骤:
客户端Socket的工作过程包含以下四个基本的步骤:
6. 创建 Socket:根据指定服务端的 IP 地址或端口号构造 Socket 类对象,创建的同时会自动向服务器方发起连接。若服务器端响应,则建立客户端到服务器的通信线路。若连接失败,会出现异常。
7. 打开连接到Socket 的输入/出流:使用 getInputStream()方法获得输入流,使用 getOutputStream()方法获得输出流,进行数据传输。
8. 进行读/写操作:通过输入流读取服务器发送的信息,通过输出流将信息发送给服务器。
9. 关闭 Socket:断开客户端到服务器的连接
####UDP(User Datagram Protocol,用户数据报协议):是一个无连接的传输层协议,提供面向事物的简单不可靠的信息传送服务
DatagramSocket常用方法: