springboot SocketServer向客户端发送数据 demo
时间: 2023-09-03 22:09:32 浏览: 107
以下是一个基本的 Spring Boot SocketServer 向客户端发送数据的 Demo:
1. 首先,需要定义一个 SocketServer 类:
```java
@Component
public class MySocketServer {
private ServerSocket serverSocket;
@Value("${mysocketserver.port}")
private int port;
@PostConstruct
public void init() {
try {
serverSocket = new ServerSocket(port);
System.out.println("SocketServer started on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket.getInetAddress().getHostAddress());
handleClient(clientSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleClient(Socket clientSocket) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received message from client: " + inputLine);
out.println("Server received message: " + inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@PreDestroy
public void destroy() {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 在 application.properties 中定义 SocketServer 的端口:
```
mysocketserver.port=8080
```
3. 在另一个类中,可以使用 Spring 的 Autowired 注解来注入 MySocketServer 实例,并调用 sendToClient 方法向客户端发送消息:
```java
@Service
public class MyService {
@Autowired
private MySocketServer socketServer;
public void sendToClient(Socket clientSocket, String message) {
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这样就可以在 MyService 中调用 sendToClient 方法向客户端发送消息了。
阅读全文