{"size": 1929, "ext": "js", "max_stars_repo_path": "web/demo/html/websocket-learn/js/chat-websocket.js", "max_stars_repo_name": "masgyw/individual-study", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "web/demo/html/websocket-learn/js/chat-websocket.js", "max_issues_repo_name": "masgyw/individual-study", "max_issues_repo_issues_event_min_datetime": "2020-06-12T02:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-22T15:48:15.000Z", "max_forks_repo_path": "web/demo/html/websocket-learn/js/chat-websocket.js", "max_forks_repo_name": "masgyw/individual-study", "max_forks_repo_forks_event_min_datetime": "2020-11-24T09:43:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T05:31:57.000Z"}
{"max_stars_count": null, "max_issues_count": 6, "max_forks_count": 2, "avg_line_length": 20.9673913043, "max_line_length": 57, "alphanum_fraction": 0.5152928979}
var websocket = null;
var fromUserId = null;
var wsUrl = "ws://localhost:8080/gtools/chat/";

$(function () {

    bindEvents();
    /* var vm = new Vue({
        el: "#chat",
        data: data,
        methods: {
            doConnect: doConnect,
            doSendMsg: doSendMsg,
            doClose: doClose
        },
        before: {
            bindEvents
        }
    }); */
});

function doSendMsg() {
    var content = $("#msgContent").val();
    var toUserId = $("#toUserId").val();
    var sendMsg = {
        "fromUserId": fromUserId,
        "toUserId": toUserId,
        "content": content
    }
    websocket.send(JSON.stringify(sendMsg));
}

function doConnect() {
    fromUserId = $("#fromUserId").val();
    console.log("userId:" + fromUserId);
    if ("WebSocket" in window) {
        var ws = wsUrl + fromUserId;
        websocket = new WebSocket(ws);
        websocket.onopen = onConnected;
        websocket.onclose = onClosed;
        websocket.onmessage = onMessage;
        websocket.onerror = onError;
    } else {
        showMessage("连接失败...")
    }
}

function doClose() {
    websocket.close();
}

function bindEvents() {
    $("button[name='wsBtn']").click(function () {
        var operType = $(this).val();
        // console.log(operType);
        switch (operType) {
            case "1":
                doConnect();
                break;
            case "2":
                doSendMsg();
                break;
            case "3":
                doClose();
                break;
            default:
                console.error("not support>" + operType);
        }
    });
}

window.onclose = doClose;

function showMessage(msg) {
    $(".content").append(msg + "<br>");
}

function onMessage(evt) {
    showMessage(evt.data);
}

function onConnected() {
    showMessage("连接成功");
}

function onClosed() {
    showMessage("连接关闭");
}

function onError() {
    showMessage("连接异常");
}