用java让客户端和服务端建立连接
时间: 2023-05-11 19:05:39 浏览: 116
可以使用 Java 中的 Socket 类来建立客户端和服务端之间的连接。以下是一个简单的示例代码:
客户端:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
System.out.println("Connected to server");
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(8888);
System.out.println("Server started");
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();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码可以让客户端和服务端建立连接,并在连接建立后互相发送消息。
阅读全文