连接
断开
格式:ws://IP或域名:端口
发送
消息
var websocket;
var wsUrl;
function connect()
{
try {
wsUrl = $('#wsUrl').val();
websocket = new WebSocket(wsUrl);
websocket.onopen = function(event)
{
console.log('客户端与服务端连接成功');
connectChangeButton();
alert('连接成功');
}
websocket.onmessage = function(event)
{
push(event.data);
}
websocket.onclose = function(event)
{
console.log('连接已关闭');
disconnectChangeButton();
}
websocket.onerror = function(event)
{
alert('无法与服务端建立连接');
console.log('错误:' + event.data);
}
} catch (e) {
alert('无法与服务端建立连接');
}
}
function disconnect()
{
websocket.close();
disconnectChangeButton();
}
function push(content)
{
if ($('#websocket-content').children('.content-item').length >= 10) {
$('#websocket-content').children('.content-item:first-child').remove();
}
$('#websocket-content').append('
}
function send()
{
var msg = $('#msg').val();
websocket.send(msg);
$('#msg').val('');
}
function connectChangeButton()
{
$('#send').removeAttr('disabled');
$('#disconnect').removeAttr('disabled');
$('#connect').attr('disabled', 'disabled');
}
function disconnectChangeButton()
{
$('#send').attr('disabled', 'disabled');
$('#connect').removeAttr('disabled');
$('#disconnect').attr('disabled', 'disabled');
}