Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 前、后用网匣连接问题_Java_Angular_Spring_Typescript_Websocket - Fatal编程技术网

Java 前、后用网匣连接问题

Java 前、后用网匣连接问题,java,angular,spring,typescript,websocket,Java,Angular,Spring,Typescript,Websocket,我有一个vpn项目,我尝试使用WebSocket创建一个带有套接字的聊天。这是控制器: @MessageMapping("/chat.send") @SendTo("/topic/public") public ChatMessage sendMessage (@Payload ChatMessage chatMessage){ return chatMessage; } @MessageMapping("/chat.newUs

我有一个vpn项目,我尝试使用WebSocket创建一个带有套接字的聊天。这是控制器:

    @MessageMapping("/chat.send")
@SendTo("/topic/public")
public ChatMessage sendMessage (@Payload ChatMessage chatMessage){
    return chatMessage;
}

@MessageMapping("/chat.newUser")
@SendTo("/topic/public")
public ChatMessage newUser(@Payload ChatMessage chatMessage,
                           SimpMessageHeaderAccessor headerAccessor) {
    // Add username in web socket session
    headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
    return chatMessage;
}
这是听众:

       private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketEventListener.class);

@Autowired
private SimpMessageSendingOperations sendingOperations;

@EventListener
public void handleWebSocketConnectListener (final SessionConnectedEvent event){
    LOGGER.info("Se creo una nueva conexion chat");
    /*final StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

    final String username = (String) headerAccessor.getSessionAttributes().get("username");

    final ChatMessage chatMessage = ChatMessage.builder()
            .type(MessageType.CONNECT)
            .sender(username)
            .build();

    sendingOperations.convertAndSend("/topic/public", chatMessage);*/
}

@EventListener
public void handleWebSocketDisconnectListener (final SessionDisconnectEvent event) {
    final StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

    final String username = (String) headerAccessor.getSessionAttributes().get("username");

    final ChatMessage chatMessage = ChatMessage.builder()
            .type(MessageType.DISCONNECT)
            .sender(username)
            .build();

    sendingOperations.convertAndSend("/topic/public", chatMessage);
}
这一个是配置:

        @Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    config.setApplicationDestinationPrefixes("/app");
    config.enableSimpleBroker("/topic"); //deberia cambiarse por el enableStompBroker
/*
        config.enableStompBrokerRelay("/topic")
                .setRelayHost("localhost")
                .setRelayPort(61613)
                .setClientLogin("guest")
                .setClientPasscode("guest");
*/
    }

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/chat").withSockJS();
}
部分评论我就这样离开了他们,因为我正在考虑如何解决这个问题

现在,客户端使用angle和socketjs通过vpn进行连接。这是angular中的代码

      export class WebSocketAPIService {

  private webSocketEndPoint: string = environment.baseurl + '/chat.newUser';
  private topic = '/topic/public';
  private stompClient: Stomp.Client;
  public mensajeRecibidoEmitter: EventEmitter<Message> = new EventEmitter<Message>();

  constructor() { }

  public _connect(): void {
    console.log('Initialize WebSocket Connection');
    const ws = new SockJS(this.webSocketEndPoint);
    this.stompClient = Stomp.over(ws);

    this.stompClient.connect({}, (frame: Frame) => {
      this.stompClient.subscribe(this.topic, (sdkEvent: Message) => {
        this.onMessageReceived(sdkEvent);
      });
      // _this.stompClient.reconnect_delay = 2000;
    }, (err) => this.errorCallBack(err));
  }

  public _disconnect(): void {
    if (this.stompClient !== null) {
      this.stompClient.disconnect(() => {
        console.log('Disconnected');

      });
    }
  }

  // on error, schedule a reconnection attempt
  errorCallBack(error) {
    console.log('errorCallBack -> ' + error);
    setTimeout(() => {
      // this._connect();
      console.log(' trying reconnect...');
    }, 5000);
  }

  _send(message) {
    console.log('calling logout api via web socket');
    this.stompClient.send('/app/hello', {}, JSON.stringify(message));
  }

  onMessageReceived(message: Message): void {
    console.log('Message Recieved from Server :: ' + message);
    // this.appComponent.handleMessage(JSON.stringify(message.body));
    this.mensajeRecibidoEmitter.emit(message);
  }
}
导出类WebSocketAPIService{
私有webSocketEndPoint:string=environment.baseurl+'/chat.newUser';
私有主题='/topic/public';
私有stompClient:Stomp.Client;
public-mensajeRecibidoEmitter:EventEmitter=new-EventEmitter();
构造函数(){}
public\u connect():void{
log('初始化WebSocket连接');
const ws=new SockJS(this.webSocketEndPoint);
this.stompClient=Stomp.over(ws);
this.stompClient.connect({},(frame:frame)=>{
this.stompClient.subscribe(this.topic,(sdkEvent:Message)=>{
此.onMessageReceived(sdkEvent);
});
//_this.stompClient.reconnect_delay=2000;
},(err)=>this.errorCallBack(err));
}
public\u disconnect():void{
if(this.stompClient!==null){
此.stompClient.disconnect(()=>{
console.log('Disconnected');
});
}
}
//出现错误时,计划重新连接尝试
errorCallBack(错误){
log('errorCallBack->'+error);
设置超时(()=>{
//这个;
log('正在尝试重新连接…');
}, 5000);
}
_发送(消息){
log(“通过web套接字调用注销api”);
this.stompClient.send('/app/hello',{},JSON.stringify(message));
}
onMessageReceived(消息:消息):无效{
log('从服务器接收的消息::'+消息);
//this.appComponent.handleMessage(JSON.stringify(message.body));
this.mensajeRecibidoEmitter.emit(message);
}
}
然后抛出这个错误:

访问位于“”的XMLHttpRequesthttp://192.168.100.71:8080/dpo_backend_dev/chat.newUser/info?t=1603389915235“起源”http://localhost:4200'已被CORS策略阻止:当请求的凭据模式为'include'时,响应中的'Access Control Allow Origin'标头的值不得为通配符'*'。XMLHttpRequest启动的请求的凭据模式由withCredentials属性控制


我不知道如何解决这个问题,因为我正在学习使用webSocket,但出于某种原因,我只听localhosty中发生的事情,而不是vpn之间的连接。有什么帮助吗?

我相信这里已经有答案了。我试过我说的话,但没有用,它甚至一直跳到同样的错误。我无法让他直接建立连接。错误表明没有为surenow saids配置CORS:“JWT令牌不以承载字符串开头”,但我将其作为公共端点。因此不需要令牌。是否从FE发送无效令牌?你可以在devtools中检查这个,我想我相信这里已经有答案了,我试过我说的,但是没有用,它甚至一直跳到相同的错误。我无法让他直接建立连接。错误表明没有为surenow saids配置CORS:“JWT令牌不以承载字符串开头”,但我将其作为公共端点。因此不需要令牌。是否从FE发送无效令牌?我想你可以在devtools中查看这个