制作一个客户端服务器的Java应用程序。

bluesky10月前 ⋅ 163 阅读

ChatGPT的回答仅作参考:

这是一个简单的客户端服务器Java应用程序的示例:

客户端代码:

```java
import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 8000);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println("Hello, server!");
            String response = in.readLine();
            System.out.println("Server response: " + response);
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

服务器代码:

```java
import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8000);
            System.out.println("Server started.");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Client connected.");
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                String request = in.readLine();
                System.out.println("Client request: " + request);
                out.println("Hello, client!");
                socket.close();
                System.out.println("Client disconnected.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

这个应用程序创建了一个简单的客户端和服务器,客户端连接到服务器并发送一条消息,服务器接收到消息并发送一条响应消息。客户端和服务器都使用了Java的Socket类来进行网络通信。

全部评论: 0

    相关推荐