Java Socket网络编程基础知识InetAddress、端口号及TCP/IP协议
作者:野牛程序员:2023-12-28 10:53:54java阅读 3034
Socket网络编程中,InetAddress类用于表示IP地址,而端口号则是用来标识在一台主机上运行的多个应用程序中的特定应用程序。TCP/IP协议是一组用于在网络上进行通信的协议。
InetAddress类用于标识网络上的主机。可以通过以下方式获取InetAddress对象:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressExample {
public static void main(String[] args) {
try {
// 通过主机名获取InetAddress对象
InetAddress address = InetAddress.getByName("www.example.com");
// 获取主机名
String hostName = address.getHostName();
System.out.println("Host Name: " + hostName);
// 获取IP地址的字节数组形式
byte[] ipAddress = address.getAddress();
System.out.println("IP Address: " + InetAddress.getByAddress(ipAddress));
// 获取主机的完全限定域名(FQDN)
System.out.println("Canonical Host Name: " + address.getCanonicalHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}端口号用于标识一个主机上的应用程序。在Socket编程中,客户端和服务器之间的通信通过端口号进行。以下是一个简单的Socket服务器和客户端的示例:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
// 创建服务器Socket,绑定端口号
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server 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());
// 关闭连接
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
// 创建Socket,指定服务器地址和端口号
Socket client = new Socket("localhost", 12345);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
// 获取输出流,发送数据到服务器
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
// 关闭连接
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}在这个例子中,服务器通过ServerSocket监听端口号12345,并等待客户端连接。客户端通过Socket连接到服务器的IP地址和端口号,然后发送数据到服务器。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

