如何在Java中通过InetAddress类获取本机IP地址,并利用Socket和ServerSocket实现一个简单的TCP/IP客户端-服务器通信模型?
时间: 2024-12-06 19:30:18 浏览: 25
在Java网络编程中,获取本机IP地址和建立客户端-服务器模型是常见的实践。利用InetAddress类可以很简单地获取本机IP地址。以下是获取本机IP地址的示例代码:
参考资源链接:[Java网络编程与数据库基础教程](https://wenku.csdn.net/doc/1hdh3br7gf?spm=1055.2569.3001.10343)
```java
InetAddress localHost = InetAddress.getLocalHost();
String address = localHost.getHostAddress();
System.out.println(
参考资源链接:[Java网络编程与数据库基础教程](https://wenku.csdn.net/doc/1hdh3br7gf?spm=1055.2569.3001.10343)
相关问题
Java实现使用ServerSocket类和Socket类以及InetAddress类编写一个GUI实现一个简单的聊天程序
好的,我来回答你的问题。
首先,我们需要了解一下 ServerSocket、Socket 和 InetAddress 这三个类的作用:
- ServerSocket:用于监听客户端的连接请求,并创建对应的 Socket 对象进行通信。
- Socket:用于与服务器建立连接并进行通信。
- InetAddress:用于表示 IP 地址。
接下来,我们可以开始编写聊天程序了。下面是一个简单的 Java 聊天程序的代码:
1. 服务器端代码:
```java
import java.io.*;
import java.net.*;
import javax.swing.*;
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
// 构造方法
public Server() {
super("Server");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(event -> sendMessage(event.getActionCommand()));
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300, 150);
setVisible(true);
}
// 启动服务器
public void startRunning() {
try {
server = new ServerSocket(7777, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (EOFException eofException) {
showMessage("\nServer ended the connection!");
} finally {
closeCrap();
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
// 等待连接
private void waitForConnection() throws IOException {
showMessage("Waiting for someone to connect...\n");
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress().getHostName());
}
// 设置流
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams are now setup!\n");
}
// 聊天
private void whileChatting() throws IOException {
String message = "You are now connected!";
sendMessage(message);
ableToType(true);
do {
try {
message = (String) input.readObject();
showMessage("\n" + message);
} catch (ClassNotFoundException classNotFoundException) {
showMessage("\nUnknown object type received!");
}
} while (!message.equals("CLIENT - END"));
}
// 关闭连接
private void closeCrap() {
showMessage("\nClosing connections...\n");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
// 发送消息
private void sendMessage(String message) {
try {
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSERVER - " + message);
} catch (IOException ioException) {
chatWindow.append("\nERROR: Cannot send message!");
}
}
// 更新聊天窗口
private void showMessage(String message) {
SwingUtilities.invokeLater(() -> chatWindow.append(message));
}
// 是否可以输入
private void ableToType(boolean tof) {
SwingUtilities.invokeLater(() -> userText.setEditable(tof));
}
}
```
2. 客户端代码:
```java
import java.io.*;
import java.net.*;
import javax.swing.*;
public class Client extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;
// 构造方法
public Client(String host) {
super("Client");
serverIP = host;
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(event -> sendMessage(event.getActionCommand()));
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300, 150);
setVisible(true);
}
// 连接到服务器
public void startRunning() {
try {
connectToServer();
setupStreams();
whileChatting();
} catch (EOFException eofException) {
showMessage("\nClient terminated the connection!");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
closeCrap();
}
}
// 连接到服务器
private void connectToServer() throws IOException {
showMessage("Attempting connection...\n");
connection = new Socket(InetAddress.getByName(serverIP), 7777);
showMessage("Connected to: " + connection.getInetAddress().getHostName());
}
// 设置流
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams are now setup!\n");
}
// 聊天
private void whileChatting() throws IOException {
ableToType(true);
do {
try {
message = (String) input.readObject();
showMessage("\n" + message);
} catch (ClassNotFoundException classNotFoundException) {
showMessage("\nUnknown object type received!");
}
} while (!message.equals("SERVER - END"));
}
// 关闭连接
private void closeCrap() {
showMessage("\nClosing connections...\n");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
// 发送消息
private void sendMessage(String message) {
try {
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " + message);
} catch (IOException ioException) {
chatWindow.append("\nERROR: Cannot send message!");
}
}
// 更新聊天窗口
private void showMessage(String message) {
SwingUtilities.invokeLater(() -> chatWindow.append(message));
}
// 是否可以输入
private void ableToType(boolean tof) {
SwingUtilities.invokeLater(() -> userText.setEditable(tof));
}
}
```
以上就是一个使用 ServerSocket 类和 Socket 类以及 InetAddress 类编写的简单聊天程序的代码。
用java编写程序,实现基于TCP/IP协议的Socket通信过程。服务器端开放: IP地址:127.0.0.1 端口号:8889 客户端发送数据: Hello Server!
好的,以下是Java代码实现:
服务器端:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8889, 10, InetAddress.getByName("127.0.0.1"));
System.out.println("服务器已启动,等待客户端连接...");
} catch (IOException e) {
System.out.println("服务器启动异常:" + e.getMessage());
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println("客户端连接成功,地址为:" + clientSocket.getInetAddress().getHostAddress());
} catch (IOException e) {
System.out.println("客户端连接异常:" + e.getMessage());
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("客户端发送数据:" + inputLine);
out.println("服务端已收到数据:" + inputLine);
if (inputLine.equals("Bye.")) {
break;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
客户端:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("127.0.0.1", 8889);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("未知的主机地址:" + e.getMessage());
System.exit(1);
} catch (IOException e) {
System.out.println("无法连接到服务器:" + e.getMessage());
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("发送数据:" + userInput);
System.out.println("服务端返回数据:" + in.readLine());
if (userInput.equals("Bye.")) {
break;
}
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
```
当客户端运行后,输入"Hello Server!",即可与服务器进行通信。
阅读全文