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

Java中网络编程的相关函数

发布时间:2023-05-30 23:41:07

Java中的网络编程是指运用Java语言及其相关的库和工具进行网络通信的一种技术。Java提供了丰富的网络编程相关函数,使得开发者可以快速地构建出各种网络应用程序。下面我们来介绍一些常用的Java网络编程函数。

1. Socket

Socket类是Java网络编程的核心类之一,它封装了TCP/IP协议,使得程序员可以通过Socket对象来实现网络通信。在Java中,Socket类支持多种网络协议,包括TCP、UDP、ICMP等。

Socket类有两个重要的构造函数:Socket(String host, int port)和Socket(InetAddress address, int port)。其中, 个构造函数用于建立基于主机名和端口号的Socket连接,而第二个构造函数用于建立基于IP地址和端口号的Socket连接。具体用法可以参考下面的代码:

import java.net.*; 
import java.io.*; 
 
public class SocketClient { 
    public static void main(String[] args) { 
        try { 
            Socket socket = new Socket("localhost", 1234); // 建立主机名为localhost,端口号为1234的Socket连接
            OutputStream outToServer = socket.getOutputStream(); 
            DataOutputStream out = new DataOutputStream(outToServer); 
 
            out.writeUTF("Hello from " + socket.getLocalSocketAddress()); 
            InputStream inFromServer = socket.getInputStream(); 
            DataInputStream in = new DataInputStream(inFromServer); 
 
            System.out.println("Server says " + in.readUTF()); 
            socket.close(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
    } 
}

2. ServerSocket

ServerSocket类也是Java网络编程的一个核心类,它用于创建服务器端的Socket对象。一个ServerSocket对象监听某个端口上的连接请求,当有客户端请求时,就会建立一个对应的Socket对象,使客户端和服务器端进行通信。

ServerSocket类有一个重要的构造函数:ServerSocket(int port),用于创建一个监听端口为port的ServerSocket对象。具体用法可以参考下面的代码:

import java.net.*; 
import java.io.*; 
 
public class SocketServer extends Thread { 
    private ServerSocket serverSocket; 
 
    public SocketServer(int port) throws IOException { 
        serverSocket = new ServerSocket(port); 
        serverSocket.setSoTimeout(10000); // 设置超时时间为10秒
    } 
 
    public void run() { 
        while(true) { 
            try { 
                System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "..."); 
                Socket server = serverSocket.accept(); // 等待客户端请求
                System.out.println("Just connected to " + server.getRemoteSocketAddress()); 
                DataInputStream in = new DataInputStream(server.getInputStream()); 
                System.out.println(in.readUTF()); 
                DataOutputStream out = new DataOutputStream(server.getOutputStream()); 
                out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "
Goodbye!"); 
                server.close(); 
            } catch (SocketTimeoutException s) { 
                System.out.println("Socket timed out!"); 
                break; 
            } catch (IOException e) { 
                e.printStackTrace(); 
                break; 
            } 
        } 
    }
 
    public static void main(String[] args) { 
        int port = 1234; 
        try { 
            Thread t = new SocketServer(port); 
            t.start(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
    } 
}

3. DatagramSocket

DatagramSocket类用于支持UDP协议,它封装了UDP协议的数据报套接字。与TCP协议不同,UDP协议不需要建立连接,可以直接发送和接收数据包。DatagramSocket类也有一个构造函数:DatagramSocket(int port),用于创建一个监听端口为port的DatagramSocket对象。具体用法可以参考下面的代码:

import java.net.*; 
import java.io.*; 
 
public class DatagramServer { 
    public static void main(String[] args) throws IOException { 
        DatagramSocket serverSocket = new DatagramSocket(1234); 
 
        while(true) { 
            byte[] receiveData = new byte[1024]; 
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
            serverSocket.receive(receivePacket); 
 
            String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength()); 
            System.out.println("RECEIVED: " + sentence); 
 
            InetAddress IPAddress = receivePacket.getAddress(); 
            int port = receivePacket.getPort(); 
            String capitalizedSentence = sentence.toUpperCase(); 
            byte[] sendData = capitalizedSentence.getBytes(); 
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); 
 
            serverSocket.send(sendPacket); 
        } 
    } 
}

4. URL

URL类封装了一个URL地址,可以用来访问互联网上的资源。它提供了许多方法来获取URL中的各种信息,如主机名、端口号、路径等。它的一个重要构造函数为:URL(String spec),即用指定的字符串创建URL对象。具体用法可以参考下面的代码:

import java.net.*; 
import java.io.*; 
import javax.net.ssl.HttpsURLConnection; 
 
public class URLDemo { 
    public static void main(String[] args) throws Exception { 
        URL url = new URL("https://www.baidu.com/"); 
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); 
 
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
 
        String inputLine; 
        while ((inputLine = in.readLine()) != null) { 
            System.out.println(inputLine); 
        } 
        in.close(); 
    } 
}

5. InetAddress

InetAddress类用于表示IP地址,它提供了许多方法来获取IP地址的各种信息,如主机名、IP地址等。其常用方法有getByName(String host),用于返回指定主机名对应的IP地址,和getLocalHost(),用于返回本机的IP地址。具体用法可以参考下面的代码:

import java.net.*; 
import java.io.*; 
 
public class InetAddressDemo { 
    public static void main(String[] args) throws UnknownHostException { 
        InetAddress address = InetAddress.getByName("www.baidu.com"); 
        System.out.println("Host Name: " + address.getHostName()); 
        System.out.println("IP Address: " + address.getHostAddress()); 
 
        InetAddress localAddress = InetAddress.getLocalHost(); 
        System.out.println("Local Host Name: " + localAddress.getHostName()); 
        System.out.println("Local IP Address: " + localAddress.getHostAddress()); 
    } 
}

综上所述,Java提供了丰富的网络编程相关函数,可以轻松地创建各种网络应用程序,同时也能够灵活地适应各种网络协议的使用场景。