dongxian8272 2015-03-31 15:31
浏览 45

服务器 - 客户端与PHP / JS和Android Activity的单向套接字通信?

I'm trying to build a very simple client-server system that basically features a server script running on my computer which would send messages (Strings) from time to time to the client which is my Android Activity. The client would take a certain action based on the message received. I'm very new to socket programming of this kind so please bear with me.

Currently, I'm using a PHP server script, running on a LAMPP server on Ubuntu that sends a client.html over to the Android app, which then shows the received messages using a WebView. I do not want to do this because this introduces an additional complexity of extracting the source of the html file and fishing information out of it. I tried using socket.io earlier but couldn't make it work. I don't understand why I need to use a client.html and if it's possible to just send a String message over the established connection. (Forgive my lack of knowledge here)

Just for reference, this is the code I'm working with at present-

Android Activity class file:

package com.example.websockettest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

    WebView wb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wb = (WebView)findViewById(R.id.webView1);
        wb.setWebViewClient(new WebViewClient());
        wb.loadUrl("http://192.168.43.218/websocket/client/client.html");
        //wb.loadUrl("http://192.168.0.108/websocket/client/client.html");
        wb.getSettings().setJavaScriptEnabled(true);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Client code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Echo server - Websocket Demo</title>
    <style type="text/css">
    *{margin: 0; padding: 0;}
    body{
        background-color: black;
        color: white;
        font-family: monospace;
        font-size: 16px;
    }
    #screen, #input{
        padding: 10px;
        border: 1px solid #666;
        width: 650px;
        margin: 0 auto;
    }
    #screen{
        margin-top: 10px;
        height: 300px;
        scroll: auto;
    }
    #screen p{
        margin: 2px;
    }
    input, button{
        font-size: 20px;
        padding: 3px;
    }
    .client{
        color: green;
        font-weight: bold;
    }
    .server{
        color: red;
        font-weight: bold;
    }
    </style>
    <script src="jquery-1.11.0.js"></script>
    <script>
        // Client here
        var socket = null;
        var uri = "ws://192.168.43.218:2207";
        function connect(){
            socket = new WebSocket(uri);
            if(!socket || socket == undefined) return false;
            socket.onopen = function(){
                //writeToScreen('Connected to server '+uri);
            }
            socket.onerror = function(){
                ///\writeToScreen('Error!!!');
            }
            socket.onclose = function(){
                $('#send').prop('disabled', true);
                $('#close').prop('disabled', true);
                $('#connect').prop('disabled', false);
                writeToScreen('Socket closed!');
            }
            socket.onmessage = function(e){
                writeToScreen('<span class="server">Server: </span>'+e.data);
            }
            // Enable send and close button
            $('#send').prop('disabled', false);
            $('#close').prop('disabled', false);
            $('#connect').prop('disabled', true);
        }
        function close(){
            socket.close();
        }
        function writeToScreen(msg){
            var screen = $('#screen');
            screen.append('<p>'+msg+'</p>');
            screen.animate({scrollTop: screen.height()}, 10);
        }
        function clearScreen(){
            $('#screen').html('');
        }
        function sendMessage(){
            if(!socket || socket == undefined) return false;
            var mess = $.trim($('#message').val());
            if(mess == '') return;
            writeToScreen('<span class="client">Client: </span>'+mess);
            socket.send(mess);

            // Clear input
            $('#message').val('');
        }
        $(document).ready(function(){
        socket = new WebSocket(uri);
            if(!socket || socket == undefined) return false;
            //$('#message').focus();
            //$('#frmInput').submit(function(){
            //    sendMessage();
            //});
            //$('#connect').click(function(){
               connect();
            //});
            //$('#close').click(function(){
            //    close();
            //});
            //$('#clear').click(function(){
            //    clearScreen();
            //});
        });
    </script>
</head>
<body>
    <form id="frmInput" action="" onsubmit="return false;">
        <div id="screen">
            <p>Demo echo server</p>
            <p>----------------</p>
        </div>
        <div id="input">
            <input type="text" id="message" placeholder="Message here..">
            <button type="submit" id="send" disabled>Send</button>
            <button type="button" id="connect">Connect</button>
            <!--<button type="button" id="close" disabled>Close</button>
            <button type="button" id="clear">Clear</button>-->
        </div>
    </form>
</body>
</html>

and finally, the server code:

<?php

require "PHP-Websockets/websockets.php";

class Server extends WebSocketServer
{
    private $_connecting = 'Connecting to server..';
    private $_welcome = 'Hello, welcome to echo server!';

    protected function connected($user)
    {
        // Send welcome message to user
        $this->send($user, 'hi one');
        $this->send($user, 'hi two');
        $this->send($user, 'hi three');
        $this->send($user, 'hi four');
    }    

    protected function process($user, $message)
    {
        // Upper case user message and send back to user
        $response = 'Upper case -> ' . strtoupper($message);
        //$this->send($user, 'Server: ' . $response);
    }

    protected function closed($user)
    {
        // Alert on server
        echo "User $user->id  closed connection".PHP_EOL;
    }

    public function __destruct()
    {
        echo "Server destroyed!".PHP_EOL;
    }
}


$addr = '192.168.43.218'; //'192.168.0.108';
$port = '2207';

$server = new Server($addr, $port);
$server->run();

I need to keep this very simple and straightforward. How can I build a simple PHP/Node.js server script that could communicate with a java client file on my Android app and receive messages? A detailed explanation of how can I approach this will be most appreciated!

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!