websocket协议从远程计算机访问

时间:2013-05-10 07:45:12

标签: websocket client xampp

我设计了一个基于websocket协议的聊天应用程序。

我在计算机A中安装了xampp服务器。我在计算机A中启动服务器,然后我尝试使用ip地址从计算机B访问client.php页面(url是ipadresssofA / project / client.php)计算机A.但它显示套接字错误。

当我在电脑A上尝试相同的网址时(网址为ipadresssofA / project / client.php)。客户端连接。两台计算机都连接相同的WIFI。 这是我的客户端代码。请告诉我有什么问题

<html>
<head>


<style>

 #chatlog {width:440px; height:200px; border:1px solid;overflow:auto;}
  #userslog {width:440px; height:200px; border:1px solid;overflow:auto;}
 #msg {width:330px; height:100px;}
</style>

<script>



function initialize(){
  var host = "ws://localhost:12345/project/server3z.php";
  try{
    socket = new WebSocket(host);
    chatlog('WebSocket - status '+socket.readyState);
    socket.onopen    = function(event){chatlog("WebSocket status "+this.readyState); };
    socket.onmessage = function(event){ chatlog(event.data); };
    socket.onclose   = function(){ chatlog("WebSocket  status "+this.readyState); };
socket.onerror    = function(event){chatlog("Error :"+event.data); };
  }
  catch(err){ chatlog(err); }

}

function send()
{
  var chat;

  chat= document.getElementById("msg").value;
  if(!chat){ alert("Message can not be empty"); return; }

  try{ socket.send(chat); chatlog('Sent: '+chat); } catch(err){ log(err); }
  document.getElementById("msg").value = "";
}
function quit(){
  chatlog("closed!");
  socket.close();
  chatlog("WebSocket  status "+socket.readyState);

}



function chatlog(msg)
{
var match=msg.match(/10101010101010/g);
if(match)
{
var msg=msg.split("10101010101010");
document.getElementById("userslog").innerHTML+="<br>"+msg[0];
}
else
{
document.getElementById("chatlog").innerHTML+="<br>"+msg;
 }
 }

 function onkey(event){ if(event.keyCode==13){ send(); } }

</script>

</head>
<body onload="initialize()">
 <center>
 <div id="chatlog"></div>
 <input id="msg" type="textbox" onkeypress="onkey(event)"/>
 <button onclick="send()">Send</button>
 <button onclick="quit()">Stop</button>
 <div id="userslog"></div>
 </center>
</body>
</html>

同样在我的服务器代码中,我想向您展示一些注释:

// start the server
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
// for other computers to connect, you will probably need to change this to your LAN IP or external IP,
// alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME']))
$Server->wsStartServer('localhost', 12345);

1 个答案:

答案 0 :(得分:0)

按如下方式初始化var host:

var host =“ws:// localhost:12345”;

其他一切看起来都不错。