Java程序,两个主机实现通信
时间: 2024-03-05 21:51:42 浏览: 63
要实现两个主机之间的通信,可以使用Java中的Socket编程。下面是一个简单的示例代码:
在一个主机上创建服务器:
```java
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println("Server: " + inputLine);
}
}
}
```
在另一个主机上创建客户端:
```java
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("server_hostname", 1234);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Server: " + in.readLine());
}
}
}
```
在客户端中,将“server_hostname”替换为运行服务器的主机的名称。运行服务器和客户端程序后,可以在客户端中输入消息,然后在服务器中查看到该消息。
阅读全文