用eclipse编写 (1) 写个控制台TCP聊天程序, 服务器可以同时和多个客户机聊天, 输入 Bye串结束会话。 (2) 写个控制台程序, 服务器能接收客户机传来的圆的半径, 计算面积后, 传给客户机, 客户机 收到面积后显示结果。
时间: 2024-12-26 18:28:09 浏览: 7
在Eclipse中创建一个简单的控制台TCP聊天程序和计算圆面积的程序,你可以按照以下步骤进行:
**1. TCP聊天程序**
首先,你需要使用java.net包中的ServerSocket和Socket类来实现服务器和客户端之间的通信。这里是一个简化的示例:
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
private static final int PORT = 9090; // 设置端口
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server started on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
Thread clientHandler = new ClientHandler(clientSocket);
clientHandler.start();
}
}
private static class ClientHandler extends Thread {
private Socket socket;
public ClientHandler(Socket s) {
this.socket = s;
}
@Override
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
String message;
while ((message = in.readLine()) != null && !message.equals("Bye")) {
if (!message.isEmpty()) {
System.out.println("Received from client: " + message);
out.println("Echoing: " + message);
}
}
out.println("Goodbye!");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
阅读全文