用idea使用windows socket 编写C/S程序,具有简单的远程控制功能,给出完整代码
时间: 2024-12-22 09:26:52 浏览: 9
在IntelliJ IDEA中编写Windows Socket C/S(客户端/服务器)程序,你可以使用Java语言,因为Java内置了强大的网络通信库`java.net`,特别是`ServerSocket`和`Socket`类。以下是一个简单的示例,实现了基本的远程控制功能:
**服务器端(Server.java):**
```java
import java.io.*;
import java.net.*;
public class Server {
private static final int PORT = 9000; // 端口
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server is running on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
handleClient(clientSocket);
}
}
private static void handleClient(Socket clientSocket) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String command;
while ((command = in.readLine()) != null) {
if ("exit".equals(command)) break; // 用户退出命令
try {
// 这里处理客户端发送的控制指令,比如关闭、重启等操作
// 根据实际需求进行相应的操作,并将结果反馈给客户端
out.println("Command received: " + command);
} catch (Exception e) {
out.println("Error processing command: " + e.getMessage());
}
}
clientSocket.close();
in.close();
out.close();
}
}
```
**客户端(Client.java):**
```java
import java.io.*;
import java.net.*;
public class Client {
private static final String SERVER_IP = "localhost"; // 更改为实际服务器IP
private static final int PORT = 9000;
public static void main(String[] args) throws IOException {
Socket socket = new Socket(SERVER_IP, PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput); // 发送用户输入到服务器
System.out.println("Sent: " + userInput);
String response = in.readLine(); // 读取服务器响应
System.out.println("Received from server: " + response);
}
out.close();
stdIn.close();
in.close();
socket.close();
}
}
```
为了运行这个程序,首先在服务器上运行`Server`类,然后在客户端(通常是另一个终端窗口)运行`Client`类,通过输入命令与服务器交互。
**相关问题--:**
1. 如何在IntelliJ IDEA中设置服务器监听?
2. 如何测试这个C/S结构的应用?
3. 如果需要加密通信,如何修改上述代码?
阅读全文