InetAddress类
用来描述IP地址的类。示例:
public void test() throws UnknownHostException{
/*
* 获取本地主机的IP地址
* */
InetAddress local = InetAddress.getLocalHost();
System.out.println(local);
/*
* 根据域名获取主机的IP地址
* */
InetAddress baidu = InetAddress.getByName("www.baidu.com");
System.out.println(baidu);
}
URL类
定义了WWW资源的特征以及读其内容的方法,url是由协议,主机,端口号,文件的相对路径组成的,如:http://www.baidu.com:80/index.html,其中端口号默认为80,所以可以不写。URL类的使用:
public void test() throws IOException{
URL url = new URL("http://www.baidu.com/");
URLConnection conn = url.openConnection();
System.out.println(conn.getHeaderField(0));
System.out.println(conn.getHeaderField(1));
Scanner scanner = new Scanner(url.openStream());
while(scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
}
百度首页的文本内容就获取到了,而且可以获得请求报头等信息。
Socket类和ServerSocket类
套接字是网络协议传输层提供的接口,它是进程之间通信的抽象连接点,它封装了主机,端口号,传输层协议三方面的内涵。通信的双方,服务器的一端使用ServerSocket,而客户机一端使用Socket。
套接字可分为两种,流套接字和数据报套接字。流套接字提供了一种连接的,有序的,无重复的,无记录边界的数据流服务,数据报套接字则是相反的。
因特网上的主机都有唯一的IP地址,IP地址通过域名服务器(DNS)可以由域名转化得到。与IP协议一起工作的高层协议是TCP协议和UDP协议。java支持基于流的通信和基于数据报的通信。
示例:
import java.io.*;
import java.net.*;
public class Server {
public void start() throws IOException{
ServerSocket ss = null;
Socket s = null;
ss = new ServerSocket(7896);
while(true){
s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println(str);
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write(input.readLine()+"\n");
bw.flush();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
new Server().start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Client {
public void start() throws IOException{
Socket s = new Socket("localhost",7896);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
bw.write(input.readLine()+"\n");
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println(str);
bw.close();
br.close();
s.close();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
new Client().start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
代码有些地方不规范,但是这里着重于Socket的使用。