欢迎访问宙启技术站
智能推送

Java中的网络编程:Socket、ServerSocket和InetAddress的使用方法

发布时间:2023-06-26 20:13:56

Java中的网络编程主要涉及到三个类:Socket、ServerSocket和InetAddress。Socket和ServerSocket通常用于客户端和服务器之间的通信,而InetAddress类则用于解析域名和IP地址之间的转换。

1.Socket类

Socket类是Java中最常用的网络编程类之一,它的作用是与服务器建立连接,并进行数据传输。Socket类的构造方法有不同的形式,可以根据需要调用不同的构造方法。

创建Socket对象:

Socket socket = new Socket(服务器地址, 端口号);

创建Socket对象时需要传入服务器的IP地址和端口号,其中IP地址可以是字符串类型也可以是InetAddress类型。创建成功后,就可以调用Socket类中提供的方法进行数据传输了。

示例代码:

try {

    Socket socket = new Socket("localhost", 8888); // 创建Socket对象

    OutputStream outputStream = socket.getOutputStream(); // 获取输出流

    outputStream.write("hello, world!".getBytes()); // 发送数据

    socket.close(); // 关闭Socket对象

} catch (Exception e) {

    e.printStackTrace();

}

2.ServerSocket类

ServerSocket类是用于创建服务器的,它监听来自客户端的请求,并与客户端建立连接。ServerSocket类的构造方法有不同的形式,可以根据需要调用不同的构造方法。

创建ServerSocket对象:

ServerSocket serverSocket = new ServerSocket(端口号);

创建ServerSocket对象时需要指定服务器监听的端口号,该端口号必须是未被占用的。创建成功后,就可以调用ServerSocket类中提供的方法等待客户端连接,一旦有客户端发起连接请求,就可以与之建立连接并进行数据传输了。

示例代码:

try {

    ServerSocket serverSocket = new ServerSocket(8888); // 创建ServerSocket对象

    Socket socket = serverSocket.accept(); // 等待客户端连接

    InputStream inputStream = socket.getInputStream(); // 获取输入流

    byte[] buffer = new byte[1024];

    int len;

    while ((len = inputStream.read(buffer)) > 0) { // 读取数据

        System.out.println(new String(buffer, 0, len));

    }

    inputStream.close(); // 关闭输入流

    socket.close(); // 关闭Socket对象

    serverSocket.close(); // 关闭ServerSocket对象

} catch (Exception e) {

    e.printStackTrace();

}

3.InetAddress类

InetAddress类用于解析域名和IP地址之间的转换,可以通过它获取本机IP地址和远程主机IP地址,还可以获取主机名和域名等信息。

获取本机IP地址:

InetAddress inetAddress = InetAddress.getLocalHost();

System.out.println("本机IP地址:" + inetAddress.getHostAddress());

获取远程主机IP地址:

InetAddress inetAddress = InetAddress.getByName("www.baidu.com");

System.out.println("百度的IP地址:" + inetAddress.getHostAddress());

获取主机名和域名等信息:

InetAddress inetAddress = InetAddress.getByName("www.baidu.com");

System.out.println("主机名:" + inetAddress.getHostName());

System.out.println("域名:" + inetAddress.getCanonicalHostName());

System.out.println("地址族:" + inetAddress.getAddress());

总结

以上就是Java中网络编程常用的三个类的使用方法。Socket和ServerSocket用于建立客户端与服务器之间的连接,并进行数据传输,而InetAddress用于解析域名和IP地址之间的转换。在使用网络编程时需要注意数据传输的安全性和稳定性,防止数据被窃取或丢失。