TCP/IP参考模型
应用层 http ftp 协议
传输层 TCP UDP协议
网际层 IP协议
Tcp transmission control protocol:传输控制协议,传输前采用三次握手建立连接,是可靠的传输协议
Udp user datagram protocol: 数据报协议,不可靠协议,即发出去的协议不一定收的到,无连接:即不管对方在不在,每个包64k ,大文件会拆分。例如qq。
public class NetDemo {
public static void main(String[] args) throws Exception {
InetAddress locAdd = InetAddress.getLocalHost();
System.out.println(locAdd.getHostAddress());// 本地IP地址
System.out.println(locAdd.getHostName());
System.out.println(locAdd.isReachable(5000));
InetAddress remAdd = InetAddress.getByName("www.baidu.com"); // 获得远程InetAddress
System.out.println(remAdd.getHostAddress());
System.out.println(remAdd.getHostName());
}
}
URL读取页面html代码
public class NetDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("http", "localhost", 8080,"/index.html");
URLConnection conn = url.openConnection();
System.out.println(conn.getContentLength()); // 7662
System.out.println(conn.getContentType()); // text/html
InputStream input = url.openStream();
Scanner scan = new Scanner(input);
scan.useDelimiter("\n");
while(scan.hasNext()){
System.out.println(scan.next());
}
}
}
URLEncoder 编码
URLDecoder解码
public class NetDemo {
public static void main(String[] args) throws Exception {
String oldStr = "csdn 程序员";
String encode = URLEncoder.encode(oldStr,"UTF-8");
System.out.println("编码后的内容:"+encode);
String decode = URLDecoder.decode(encode, "UTF-8");
System.out.println("解码后的内容:"+decode);
}
}
结果:
编码后的内容:csdn+%E7%A8%8B%E5%BA%8F%E5%91%98
解码后的内容:csdn 程序员
Tcp
服务器端使用ServerSocket ,accept()方法等待客户端连接,此方法执行后服务器端进入阻塞状态,知道客户端连接后才继续执行
客户端使用Socket ,getInputstream() 获得服务器端的输出信息,服务器端通过 getOutputStream() 获得客户端输出信息
public class NetDemo {
public static void main(String[] args) throws Exception {
ServerSocket server = new ServerSocket(8888);
System.out.println("服务器在8888端口等待客户端访问");
Socket client = server.accept();
String str = "hello world";
PrintStream out = new PrintStream(client.getOutputStream());
out.println(str);
out.close();
client.close();
server.close();
}
}
运行结果:服务器在8888端口等待客户端访问
服务器程序一执行到accept()方法后,程序进入了阻塞状态,直到客户端连接后改变可以使用telnet open localhost 8888 取得服务器的输出信息
服务器端此时只处理一个请求,所以也将关闭
public class NetDemo {
public static void main(String[] args) throws Exception {
Socket client = new Socket("localhost", 8888);
BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = buf.readLine();
System.out.println("服务器端输出的内容:"+str);
buf.close();
}
}
结果:服务器端输出的内容:hello world
使用循环和多线程方式回应程序