ws 客户端 js代码

  <head>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>

<script> 
function api(title,value){
var socket = new WebSocket('ws://10.168.5.211:3000'); 
// 打开Socket 
socket.onopen = function(event) { 
  // 发送一个初始化消息
  //var dat = {user:'jin',pass:'666'}
  var t = {function:title,data:value}
  socket.send(JSON.stringify(t)); 
  socket.onmessage = function(event) { 
    console.log(event);
	//console.log(JSON.parse(event.data).data.user);
	var data = JSON.parse(event.data).data;
	var fa = JSON.parse(event.data).function;
	
    chu(fa,data);
   
  }; 

  // 监听消息
 
 
  // 监听Socket的关闭
  socket.onclose = function(event) { 
    console.log('Client notified socket has closed',event); 
  }; 
 
  // 关闭Socket.... 
  //socket.close() 
};
}
//提交数据
var dat = {user:'jin',pass:'666'}
api('add',dat);

function bu(){
var dat = {user:'admin',pass:'22222'}
api('ass',dat);
}
//处理显示
function chu(fa,data){
console.log(fa);
//写处理方法
if(fa=='add'){
var df =""
for(var i in data){
	   df+=data[i]
	}
	$('#t').html(df);
}
	
	
if(fa=='ass'){
	var dt="";
	for(var i in data){
	   dt+=data[i]
	}
	$('#r').append(dt);
	}

}




</script>
</head>
<span id='t'></span>
<button onclick="bu()">提交</button>
<span id='r'></span>

评论

刷新

友情链接