1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【メモ】WebSocket使ってみた

Posted at

はじめに

Websocket使って双方向通信ができるように実装してみました。
フロントは素のjavascriptでバックはjavaです。

javascript

test.js
var connection = new WebSocket('ws://localhost:8080/test');

connection.onopen = function(e) { 
    connection.send('test');
};

connection.onerror = function(error) { };
 

connection.onmessage = function(e) { 
    console.log('メッセージを受け取った');
    console.log(e.data);
    
};
  
connection.onclose = function() { };

java

WebSocketConfig.java
package com.example.demo.webSocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
 * WebSocketの管理
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
  /**
   * WebSocketの登録
   */
  @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(messageHandler(), "/test").setAllowedOrigins("*");
    }
  /**
   * WebSocketHandler(コントロールするクラス)を定義
   * @return WebSocketHandler
   */
    @Bean
    public WebSocketHandler messageHandler() {
        return new MessageHandler();
    }
}
package com.example.demo.webSocket;

import java.io.IOException;
import java.util.ArrayList;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
/**
 * WebSocketのHandler
 */
public class MessageHandler extends TextWebSocketHandler {

	private ArrayList< WebSocketSession > users;
    public MessageHandler(){
        users = new ArrayList<>();
    }
    /**
     * 接続確立
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("WebSocketの接続が確立しました。");
        if(users.stream()
                .noneMatch(user -> user.getId().equals(session.getId()))){
            users.add(session);
            System.out.println(session.getId());
        }
    }
    /**
     * メッセージの送受信
     */
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        System.out.println("メッセージ受信:" + message.getPayload());
        try {
            TextMessage outputMessage = new TextMessage(message.getPayload());


            for(WebSocketSession onesession :users) {
            	System.out.println(onesession.getId());
            	onesession.sendMessage(outputMessage);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 接続終了
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("WebSocketの接続が終了しました。");
        users.stream()
        .filter(user -> user.getId().equals(session.getId()))
        .findFirst()
        .ifPresent(user -> users.remove(user));
    }
}

webSocketでパッケージを作成しています↓
image.png

通信が成功すると101が返ってくるはず、、
image.png

デベロッパーツールで双方向のやりとりを見ることができます。
image.png

おわりに

javascript側でwebsocket通信を行う実装サンプルは豊富でしたが、javaでwebsocket通信を受け取る実装は試行錯誤を繰り返しました。
工夫すればチャットのようなリアルタイムで動作するアプリが作れそうですね。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?