我正在尝试将我的 Angular 应用程序连接到基于 netty-socket.io 的 java 套接字服务器,但它不工作......
我总是在“connect_error”上收到此错误:
Error: server error
at Socket.onPacket (socket.js:393)
at XHR.Emitter.emit (index.js:145)
at XHR.onPacket (transport.js:105)
at callback (polling.js:98)
at Array.forEach (<anonymous>)
at XHR.onData (polling.js:102)
at Request.Emitter.emit (index.js:145)
at Request.onData (polling-xhr.js:231)
at Request.onLoad (polling-xhr.js:282)
at XMLHttpRequest.xhr.onreadystatechange [as __zone_symbol__ON_PROPERTYreadystatechange] (polling-xhr.js:186)
我已经尝试使用socket.io-client和ngx-socket-io。
服务器端:
public static void main(String[] args) throws InterruptedException {
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(4000);
config.setOrigin("*");
final SocketIOServer server = new SocketIOServer(config);
server.addConnectListener(new ConnectListener() {
@Override
public void onConnect(SocketIOClient client) {
System.out.println(client.toString());
client.sendEvent("start", "work";
}
});
server.addEventListener("new-msg", String.class, new DataListener<String>() {
@Override
public void onData(SocketIOClient client, String data, AckRequest ackSender) throws Exception {
System.out.println(data);
}
});
server.start();
}
客户端通过socket.io-client:
app.component.ts
constructor() {
this.socket = io('http://localhost:4000');
this.socket.on('connection', function () {
console.log('client connected');
});
this.socket.on('connect_error', function(err) {
console.log("client connect_error: ", err);
});
this.socket.on('start', (message) => {
console.log(message);
});
this.socket.emit('new-msg', 'This is a new message');
ngx-socket-io客户端:
app.module.ts
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:4000',
options: {
},
}),
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
app.component.ts
import { Component } from '@angular/core';
import { Socket } from 'ngx-socket-io';
@Component({
selector: 'socket-fun-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
serverIsReady = this.socket.fromEvent<string>('start').subscribe((msg) => {
console.log(msg);
});
constructor(private socket: Socket) {
this.socket.on('connect_error', (e: any) => {
console.log('client connect_error: ', e);
});
this.socket.on('connection', () => {
console.log('client connected');
});
this.socket.emit('new-msg', 'This is a new message');
}