简体   繁体   English

在PHP中创建聊天客户端

[英]Creating a client for a chat in PHP

I'm trying to create a PHP chat, so I have server.php that starts the server on the terminal, which is listen to client connections: 我正在尝试创建一个PHP聊天室,所以我有server.php在终端上启动服务器,该服务器监听client连接:

<?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();

?>

The function client() is the code I have from a client.php file, which when I execute on the terminal, is able to send and receive messages from the server.php . 功能client()是我从client.php文件中获得的代码,当我在终端上执行该代码时,该代码便能够从server.php发送和接收消息。 Now I would like to use my main.php file, so once the user is logged in he will send messages to the server, which will reply back the messages that user haven't seen. 现在,我想使用我的main.php文件,因此,一旦用户登录,他将向服务器发送消息,服务器将回复用户未看到的消息。 When I run server.php and client.php from two different terminals, I'm able to send and receive messages, however I would like to do that using main.php , transform that reply message into a JSON object and send back to the html page where it will get appended to a textarea box. 当我从两个不同的终端运行server.phpclient.php ,我能够发送和接收消息,但是我想使用main.php做到这一点,将回复消息转换为JSON对象,然后发送回给它将附加到textarea框的html页面。 My problem is: how can I get the reply that client.php received and send it back to the html page? 我的问题是:如何获得client.php收到的答复并将其发送回html页面? When I execute it on the terminal, I have: 在终端上执行时,我有:

Enter a message to send : hello
Reply : hello

I use AJAX to send the user input in the chat, so I wanted to be able to take that message, and send it to the server, which I started on the terminal and take the reply back and forward to the webpage and append that to the text box area. 我使用AJAX在聊天中发送用户输入,因此我希望能够接收该消息,然后将其发送到服务器,该服务器是我在终端上启动的,并将回复转发并转发到网页,并将其附加到文本框区域。 How can I accomplish that? 我该怎么做? Should I start client.php as a service through main.php ? 我应该通过main.php client.php作为服务启动吗? Or should I use the client($input) function to send a message and then return what it sends, back? 还是应该使用client($input)函数发送一条消息,然后返回发送的消息,然后返回? However, I wanted that client to be running until the use logs out, because other clients may connect to the chat. 但是,我希望该client在使用注销之前一直运行,因为其他客户端可能会连接到聊天。 How can I accomplish that is kind of fuzzy for me. 我怎样才能做到这一点对我来说是模糊的。 The code in client( $input ) is the same as in client.php . client( $input )中的代码与client.php的代码相同。

Sorry for off-topic, but if you can, it would be better to use XMPP ready solution like ejabberd server with http-bind module. 抱歉,请离题,但是,如果可以的话,最好将具有XMPP的解决方案(例如ejabberd服务器)与http-bind模块一起使用。 Sure, there is some cons it such solution, but cons are greater. 当然,这种解决方案有一些缺点,但缺点更大。 Just look in this solution, maybe it will solve your problem with low cost. 只要看一下这个解决方案,也许它将以低成本解决您的问题。

see related answer with brief desc on XMPP solution 有关XMPP解决方案的简短说明,请参阅相关答案

I think I understand what's going on. 我想我知道发生了什么事。 Sounds like you might be missing a listener? 听起来您可能想念一个听众? Usually chat programs have client-side ajax that checks or "listens" for messages for a particular user at regular intervals. 通常,聊天程序具有客户端ajax,它定期检查或“监听”特定用户的消息。

For example, if someone left a message for user x in your database (or wherever you're storing messages), the you might have some javascript that calls a php script every second to see if there are any messages on the server for user x. 例如,如果有人在数据库中(或您存储消息的任何地方)为用户x留下了一条消息,则您可能有一些javascript每秒调用php脚本,以查看服务器上是否有用户x的消息。 。 If there are, you can echo the message or messages back and received them via your ajax callback function. 如果存在,您可以回传消息或消息,并通过ajax回调函数接收它们。

If you're familiar with jQuery, check out the $.get method: http://api.jquery.com/jQuery.get/ 如果您熟悉jQuery,请查看$ .get方法: http : //api.jquery.com/jQuery.get/

As i understand your question, you want to send a message from the client to the server and as soon as this message gets to the server it will reply to all clients... i'm correct??? 据我了解您的问题,您想从客户端向服务器发送消息,并且此消息一旦到达服务器,它将回复所有客户端...我是正确的???

I do some chat like using nodejs and other javascripts tech... and must say a great option here is using web sockets. 我进行一些聊天,例如使用nodejs和其他JavaScript技术...,并且必须说,使用Web套接字是一个不错的选择。 Realize that browser support is limited , but since you not specified what browsers need to run this i think a great way to go. 意识到浏览器支持是有限的 ,但是由于您未指定运行该浏览器所需要的浏览器,因此我认为这是一个不错的方法。

Check this related links: 检查此相关链接:

How to Use Sockets in JavaScript\\HTML? 如何在JavaScript \\ HTML中使用套接字?

http://socket.io/ http://socket.io/

A possible way of doing that only using php + js is make some function and put in a setInterval to make request to the server every 12 seconds. 仅使用php + js的一种可能方法是制作一些函数并放入setInterval中,以每12秒向服务器发出一次请求。 I made some kind of asp chat in 2005 that uses this approach. 我在2005年使用这种方法进行了某种形式的asp聊天。 And i must say the web socket is much better. 我必须说网络套接字要好得多。

I don't know if that answers your question... let me know! 我不知道是否能回答您的问题...让我知道!

I developed something along these lines before using PHP and jQuery. 在使用PHP和jQuery之前,我根据这些思路开发了一些东西。 The solution I went for was due to the restrictions on the server setup(out of my control). 我追求的解决方案是由于服务器设置方面的限制(超出我的控制范围)。 I used a PHP core script to create the whole layout of the page from message window to message submission box. 我使用PHP核心脚本创建了从消息窗口到消息提交框的页面整个布局。 Any user that came to the page was given a randomly generated user like user123234234 generated off a unix timestamp from the time they entered the chat page. 进入该页面的所有用户都将获得一个随机生成的用户,例如user123234234,该用户是从进入聊天页面时的unix时间戳生成的。

All messages submitted were stored in an XML file and a new XMl file was created daily. 提交的所有消息均存储在XML文件中,并且每天都会创建一个新的XMl文件。 The user was kept in a message node like below with details of the user for every message using different node attributes. 将该用户保留在如下所示的消息节点中,其中包含使用不同节点属性的每条消息的用户详细信息。

The message window was refreshed every 5 seconds using jquery AJAX call to another PHP script that read in the XML that days XML file only from the time the user entered the chat page. 使用对另一个PHP脚本的jquery AJAX调用,每5秒钟刷新一次消息窗口,该脚本以从用户进入聊天页面开始的XML文件开始读取XML文件。

<messages>
    <message user="user123456" ip="127.0.0.1" session="{users session ID here}" time="{unix timestamp}"><![CDATA[User message here]]></message>
</messages>

There is a lot more logic behind it but I found it the easiest to develop and maintain, I hope it help point you in the right direction. 它背后有更多的逻辑,但是我发现它是最容易开发和维护的逻辑,希望它能为您指明正确的方向。 And it works on all major browsers and from IE7+. 它适用于所有主流浏览器以及IE7 +。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM