JAVASCRIPT 如何实现socket,

JavaScript021

JAVASCRIPT 如何实现socket,,第1张

目前只有支持HTML5的浏览器加入了Javascript对Socket的支持, 而且目前处于测试阶段, 还不推荐使用. 如果你必须要用Javascript实现socket传输, 相关代码如下:

<!-- 初始化 -->

function connect(){

try{

var socket

var host = "ws://localhost:8000/socket/server/startDaemon.php"

var socket = new WebSocket(host)

message('<p class="event">Socket Status: '+socket.readyState)

socket.onopen = function(){

message('<p class="event">Socket Status: '+socket.readyState+' (open)')

}

socket.onmessage = function(msg){

message('<p class="message">Received: '+msg.data)

}

socket.onclose = function(){

message('<p class="event">Socket Status: '+socket.readyState+' (Closed)')

}

} catch(exception){

message('<p>Error'+exception)

}

}

<!-- 发送数据 -->

function send() {

socket.send(text)

}

<!-- 断开Socket -->

socket.close()

var socket = __import__('Socket', null, {}) //导入Socket library..

var client = new socket.Socket('127.0.0.1', 8000) //创建一个Socket.

client.on('read', function(socket){//注册读数据的事件

var echo = socket.read() //读收到的数据,,返回的结果为string对象

print('echo from server:' + echo)

socket.write("Bye!")

socket.close() //关闭socket.

})

client.on('connect', function(socket){ //注册连接成功时事件

print('connectted....')

socket.write("Hello server, i'm a client!")

})

client.on('closed', function(socket){//socket 关闭后的事件.

//client.write("Bye!")

print('Bye!')

})

client.connect() //连接服务器,,并等待触发事件,,直到socket关闭.