java实现socket连接
时间: 2023-10-26 20:06:21 浏览: 89
下面是Java实现socket连接的示例代码:
客户端:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
// 创建Socket对象,指定服务器地址和端口号
Socket socket = new Socket("localhost", 8888);
// 获取输出流,向服务器发送数据
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
pw.println("Hello, server!");
pw.flush();
// 获取输入流,读取服务器返回的数据
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = br.readLine();
System.out.println("Server response: " + response);
// 关闭连接
br.close();
pw.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
服务器端:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
// 创建ServerSocket对象,指定端口号
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started.");
while (true) {
// 监听客户端连接请求,返回Socket对象
Socket socket = serverSocket.accept();
System.out.println("Client connected.");
// 获取输入流,读取客户端发送的数据
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String request = br.readLine();
System.out.println("Client request: " + request);
// 获取输出流,向客户端发送数据
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
pw.println("Hello, client!");
pw.flush();
// 关闭连接
br.close();
pw.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文