All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fastchar.socket.core.FastWebSocket Maven / Gradle / Ivy

package com.fastchar.socket.core;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.ArrayList;
import java.util.List;

public class FastWebSocket {

    private final Channel channel;
    private final String url;

    private final List onSendListeners = new ArrayList<>();

    public FastWebSocket(Channel channel, String url) {
        this.channel = channel;
        this.url = url;
    }

    public Channel getChannel() {
        return channel;
    }

    public String getUrl() {
        return this.url;
    }

    public FastWebSocket addListener(OnSendListener onSendListener) {
        if (onSendListeners.contains(onSendListener)) {
            return this;
        }
        onSendListeners.add(onSendListener);
        return this;
    }

    public FastWebSocket removeListener(OnSendListener onSendListener) {
        onSendListeners.remove(onSendListener);
        return this;
    }

    public List getListeners() {
        return onSendListeners;
    }

    public boolean close() {
        if (channel == null) {
            return false;
        }
        channel.close();
        return true;
    }

    public boolean send(String message) {
        if (channel == null) {
            return false;
        }
        channel.writeAndFlush(new TextWebSocketFrame(message));
        for (OnSendListener onSendListener : onSendListeners) {
            if (onSendListener == null) {
                continue;
            }
            onSendListener.onSendMessage(this, message);
        }
        return true;
    }

    @Override
    public String toString() {
        return "FastWebSocket{" +
                "channel=" + channel +
                ", url='" + url + '\'' +
                '}';
    }


    public interface OnSendListener {

        void onSendMessage(FastWebSocket webSocket,String message);
    }
}






© 2015 - 2024 Weber Informatics LLC | Privacy Policy