javase 里面关于网络的基础类说明(工作中基本用不到,看着图个乐就行)
常用类
InetAddress
This class represents an Internet Protocol (IP) address.
//获取主机名/IP
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
//获取主机名/IP
InetAddress inetAdd = InetAddress.getByName("www.baidu.com");
System.out.println(inetAdd);
//IP
System.out.println(inetAdd.getHostAddress());
//主机名
System.out.println(inetAdd.getHostName());
//执行结果
// losssdeMac-mini.local/192.168.1.6
// www.baidu.com/119.63.197.139
// 119.63.197.139
// www.baidu.com
Socket
This class implements client sockets (also called just “sockets”). A socket is an endpoint for communication between two machines.
通过客户端和服务端的交互例子来说明常用方法
//client
public class Client {
public static void main(String[] args) throws IOException {
//向Server送数据
Socket socket =new Socket("127.0.0.1",2222);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello server".getBytes());
//接收Server返回
InputStream inputStream = socket.getInputStream();
byte [] buff=new byte[1024];
int length=inputStream.read(buff);
System.out.println(new String(buff,0,length));
inputStream.close();
outputStream.close();
socket.close();
}
}
//server
public class Server {
public static void main(String[] args) throws IOException {
//打开Server接收数据
ServerSocket serverSocket =new ServerSocket(2222);
//获取服务端的套接字对象
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
byte[] buff = new byte[1024];
int length=inputStream.read(buff);
System.out.println(new String(buff,0,length));
//向Clinet送数据
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello Client".getBytes());
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}