Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //variable to know where the user is
- $chosen = 0;
- echo "Enter a username on which you will receive the messages! \r\n";
- //asks for a user input
- $user = fgets(STDIN, 1024);
- //removing new line
- $user = rtrim($user, "\n\r");
- //while to keep the script always running
- while ($chosen === 0) {
- //shows a list of commands
- echo "\r\n\r\n\r\nYou are logged in as $user \r\n
- List of commands: \r\n
- /send ~~ To send a message \r\n
- /receive ~~ To receive a message \r\n
- /exit ~~ To close the chat\r\n\r\n\r\n";
- //asks for user input
- $command = fgets(STDIN, 1024);
- //removing new line
- $command = rtrim($command, "\n\r");
- //setting chosen based on user input
- if ($command === '/send') {
- $chosen = 1;
- }
- if ($command === '/receive') {
- $chosen = 2;
- }
- if ($command === '/exit') {
- $chosen = 3;
- }
- // Action for the /send command
- while ($chosen === 1) {
- echo "Type /back to go back\n\r";
- //asks for user input so I know where to send the message
- echo 'Destination:';
- $destination = fgets(STDIN);
- $destination = rtrim($destination, "\n\r");
- if ($destination === '/back') {
- $chosen = 0;
- break;
- }
- //asks for the message content
- echo "Message\r\n";
- $message = fgets(STDIN);
- $message = rtrim($message, "\n\r");
- echo "\r\n";
- if ($message === '/back') {
- $chosen = 0;
- break;
- } else {
- //connects to the JMS server
- try {
- $stomp = new Stomp('tcp://localhost:61613');
- while (true) {
- //sends the message to the JMS server
- $stomp->send($destination, $message, array('sent_by' => $user));
- //break so it only sends it once
- break;
- }
- } catch (StompException $e) {
- die('Connection error: '.$e);
- }
- }
- }
- // Action for the /receive command
- while ($chosen === 2) {
- //sets the queue to the chosen username
- $queue = $user;
- //connects to the JMS server
- $stomp = new Stomp('tcp://127.0.0.1:61613');
- $stomp->subscribe($queue);
- while ($stomp->hasFrame()) {
- $frame = $stomp->readFrame();
- if ($frame != null) {
- //prints out the messages
- echo "Sent by: ".$frame->headers['sent_by']."\r\n";
- echo "Message: ".$frame->body."\r\n\r\n\r\n";
- $stomp->ack($frame);
- }
- }
- if (!$stomp->hasFrame()){
- echo "No new messages\r\n\r\n\r\n";
- }
- $chosen = 0;
- }
- //exit
- if ($chosen === 3) {
- die;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement