InetAddress类
InetAddress类的中未提供公开的构造方法,因此无法直接new对象;其常用静态方法如下:
- getLocalHost() 获取本地主机对象
- getByName(String host) 根据主机名(或ip)获取InetAddress对象
- getByAddress(byte[] b) 根据字节数组获取InetAddress对象
- getByAddress(String host,byte[] b) 根据主机名称和ip的字节数组获取InetAddress对象
public class InetAddressDemo {
public static void main(String[] args) throws UnknownHostException {
//获取本地主机对象 localhost
InetAddress ip = InetAddress.getLocalHost();
System.out.println(ip);
//获取主机名(计算名)
System.out.println(ip.getHostName());
//获取主机地址(ip)
System.out.println(ip.getHostAddress());
//获取回送地址
System.out.println(InetAddress.getLoopbackAddress());
ip = InetAddress.getByName("mrchai");
System.out.println(ip);
byte[] b = new byte[]{(byte)192,(byte)168,(byte)0,(byte)198};
ip = InetAddress.getByAddress(b);
System.out.println(ip);
ip = InetAddress.getByAddress("mrchai", b);
System.out.println(ip);
}
}
Socket通信
Socket(套接字)是主机中ip和端口结合,通过Socket可以轻松实现不同主机之间应用程序的通信,可以通俗的理解为不同主机中相同软件的的通信桥梁,关于计算机应用的通信模式分为以下两种:
- C/S架构:客户端(Client)/服务端(Server)模式。
- B/S架构:浏览器(Browser)/服务器(Server)模式。
服务端
public class MyServer {
public static void main(String[] args) throws IOException {
// ServerSocket server = new ServerSocket();
// server.bind(new InetSocketAddress(8888));
//占据8888端口创建一个服务 192.168.4.198
ServerSocket server = new ServerSocket(8888);
System.out.println("服务已创建,等待连接...");
//循环监听
while(true){
//开始监听,一旦客户端连接则返回Socket对象
Socket s = server.accept();
System.out.println("客户端已连接!"+s.getInetAddress());
//获取Socket的输出流
OutputStream os = s.getOutputStream();
//将字节输出流包装为打印流
PrintWriter pw = new PrintWriter(os);
pw.println("欢迎使用SOFTEEM不知道干啥的服务器。。。");
pw.flush();
pw.close();
}
}
}
客户端
public class MyClient {
public static void main(String[] args) throws UnknownHostException, IOException {
//连接到指定ip,指定端口的服务
Socket s = new Socket("192.168.4.198",8888);
//获取基于Socket的字节输入流
InputStream is = s.getInputStream();
//将字节流转换为字符流
InputStreamReader isr = new InputStreamReader(is);
//将低级字符流转换为缓冲流
BufferedReader br = new BufferedReader(isr);
String msg = br.readLine();
System.out.println(msg);
}
}