可以后端用springboot,前端用angular再写一个例子吗
时间: 2024-03-14 12:43:06 浏览: 20
当然可以!下面是一个使用 Spring Boot 和 Angular 实现的示例,实现了一个简单的实时聊天应用。
后端代码(使用 Spring Boot 和 Spring WebSocket):
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
private ChatHandler chatHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatHandler, "/chat").setAllowedOrigins("*");
}
}
@Component
public class ChatHandler extends TextWebSocketHandler {
private static final List<WebSocketSession> sessions = new ArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
for (WebSocketSession s : sessions) {
if (s.isOpen()) {
s.sendMessage(message);
}
}
}
}
@SpringBootApplication
public class ChatApplication {
public static void main(String[] args) {
SpringApplication.run(ChatApplication.class, args);
}
}
```
这段代码中,`WebSocketConfig` 类用于注册 WebSocket 处理器,并将其映射到 `/chat` 路径。`ChatHandler` 类是 WebSocket 处理器,维护了一个静态的 `sessions` 列表,用于存储所有客户端的 WebSocket 会话。当有新的客户端连接时,会将其会话添加到 `sessions` 列表中。当客户端断开连接时,会将其会话从 `sessions` 列表中移除。处理文本消息时,会将消息发送给所有客户端。
前端代码(使用 Angular 和 ngx-socket-io 库):
```html
<div *ngFor="let message of messages">
{{ message }}
</div>
<input type="text" [(ngModel)]="input" (keydown.enter)="send()">
<button (click)="send()">Send</button>
```
```typescript
import { Component } from '@angular/core';
import { Socket } from 'ngx-socket-io';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
messages: string[] = [];
input: string = '';
constructor(private socket: Socket) {
this.socket.fromEvent<string>('message').subscribe(message => {
this.messages.push(message);
});
}
send() {
if (this.input.trim() === '') {
return;
}
this.socket.emit('message', this.input);
this.input = '';
}
}
```
这段代码中,`AppComponent` 组件维护了一个 `messages` 数组,用于存储所有收到的消息,以及一个 `input` 变量,用于输入消息。在构造函数中,通过 `Socket` 服务订阅了 `message` 事件,一旦收到新消息,就将其添加到 `messages` 数组中。`send` 方法用于发送消息,当用户按下回车键或点击“Send”按钮时会被调用。在 `send` 方法中,使用 `emit` 方法向服务器发送消息。
需要注意的是,上面的代码中使用了 `ngx-socket-io` 库来处理 WebSocket 连接。在使用 `ngx-socket-io` 之前,需要先安装该库:
```
npm install ngx-socket-io --save
```
然后在 `app.module.ts` 中导入 `SocketIoModule`:
```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SocketIoModule } from 'ngx-socket-io';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
SocketIoModule.forRoot({
url: 'http://localhost:8080/chat',
options: {}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
这段代码中,导入了 `SocketIoModule`,并在 `imports` 中调用 `forRoot` 方法来配置 WebSocket 连接。`url` 参数指定 WebSocket 服务器的地址,`options` 参数可以用于配置其他选项,例如身份验证等。
最后,在命令行中启动应用:
```
mvn spring-boot:run
```
```
ng serve --open
```
然后就可以在浏览器中访问应用了。多个浏览器窗口或标签页之间可以进行实时聊天。