0

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

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

当我在计算机 A 上尝试相同的 url 时(url 是 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);
4

1 回答 1

0

初始化 var host 如下:

var host = "ws://localhost:12345";

其他一切看起来都不错。

于 2013-11-29T09:22:29.190 回答