我试图创建一个PHP
聊天的聊天,让我有server.php
启动终端上的服务器,这是听client
连接:创建一个客户端在PHP
<?php
function chat_leave($sock, $chat_id = 0)
{
if($chat_room_id[ $chat_id ])
{
unset($chat_room_id[ $chat_id ]);
return true;
}
socket_close($sock);
return false;
}
function client($input)
{
/*
Simple php udp socket client
*/
//Reduce errors
error_reporting(~E_WARNING);
$server = '127.0.0.1';
$port = 9999;
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
//Communication loop
while(1)
{
//Send the message to the server
if(! socket_sendto($sock, $input , strlen($input) , 0 , $server , $port))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n");
}
//Now receive reply from server and print it
if(socket_recv ($sock , $reply , 2045 , MSG_WAITALL) === FALSE)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
return $reply;
}
}
/*
* chat_join
* a new user joins the chat
* @username: String
* @password: String
*
* add a new listener to the server
*
*/
function chat_join($username = "", $password = "")
{
$users = array(
"batman" => "batman123",
"robin" => "robin123",
"joe" => "joe123"
);
if($users[$username] == $password)
{
return true;
}
return false;
}
function main()
{
$chat_room_id = array();
$username = stripslashes($_POST['username']);
$password = stripslashes($_POST['password']);
$action = stripslashes($_POST['action']);
$port = intval($_POST['port']);
$domain = stripslashes($_POST['domain']);
$chat_id = intval($_POST['chat_room_id']);
if(strcmp($action, "login") == 0)
{
$status = chat_join($username, $password);
if($status)
{
$chat_room_id[] = $chat_id;
echo json_encode($status);
}
}
else if(strcmp($action, "chat") == 0)
{
$msg = stripslashes($_POST['message']);
// take the message, send through the client
$reply = client($msg);
echo json_encode($reply);
}
else if(strcmp($action, "logout") == 0)
{
}
else
{
echo json_encode(false);
}
return;
}
main();
?>
功能client()
是我从client.php
文件得到的代码,当我在终端上执行时,它能够发送和接收来自server.php
的消息。现在我想使用我的main.php
文件,因此一旦用户登录,他将向服务器发送消息,服务器将回复用户没有看到的消息。 当我从两个不同的终端运行server.php
和client.php
时,我可以发送和接收消息,但是我希望使用main.php
来执行此操作,将该消息转换为JSON
对象并发送回html
页面,附加到textarea
框中。 我的问题是:如何获得client.php
收到的回复并将其发送回html页面? 当我执行它在终端上,我有:
Enter a message to send : hello
Reply : hello
我用AJAX
发送用户输入在聊天,所以我希望能够把这一信息,并将其发送到服务器,我开始在终端上回复并转发到网页,并将其附加到文本框区域。 我该怎么做到这一点?我是否应该通过main.php
作为服务启动client.php
?或者我应该使用client($input)
函数发送一条消息,然后返回它发送的消息? 但是,我希望client
在用户注销之前一直运行,因为其他客户端可能会连接到该聊天。我怎么能做到这一点对我来说是模糊的。 client($input)
中的代码与client.php
中的代码相同。
http://stackoverflow.com/questions/2055020/php-chat-client – sdolgy
还要记住,PHP的设计不是运行时间超过一个请求。是否可以运行更长时间(前一段时间做过聊天机器人),但是如果你不是非常小心的话,你有很高的内存泄漏和崩溃风险。 其他语言可能更适合驻留应用程序。 – ToBe