1

我正在开发一个带有 Socket 连接的 android 应用程序。我使用示例服务器和 android 客户端(http://myandroidsolutions.blogspot.nl/2012/07/android-tcp-connection-tutorial.html)在 Internet 上进行了教程。

本教程完美运行。

但我正在尝试使用相同的 android 客户端联系人连接到 Node.js 套接字 io 服务器。我可以用它发送消息,但是当服务器每秒发送一个 ping 时我无法接收。

为什么它不起作用?我究竟做错了什么?

Node.js 套接字 io 服务器工作正常,iPhone 版本的应用程序可以发送和接收。

所有端口都是开放的。

有人能帮助我吗?感谢你!

资源

TCPClient.java

 public class TCPClient {

    private String serverMessage;
    public static final String SERVERIP = "*ip-addres*"; //your computer IP address
    public static final int SERVERPORT = 4444;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    PrintWriter out;
    BufferedReader in;

    /**
     *  Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     * @param message text entered by client
     */
    public void sendMessage(String message){
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
        }
    }

    public void stopClient(){
        mRun = false;
    }

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVERIP);

            Log.e("TCP Client", "C: Connecting...");

            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVERPORT);

            try {

                //send the message to the server
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                Log.e("TCP Client", "C: Sent.");

                Log.e("TCP Client", "C: Done.");

                //receive the message which the server sends back
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }


                Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");


            } catch (Exception e) {

                Log.e("TCP", "S: Error", e);

            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
            }

        } catch (Exception e) {

            Log.e("TCP", "C: Error", e);

        }

    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }}

聊天活动.java

    public class ChatActivity extends Activity{
 private ListView mList;
    private ArrayList<String> arrayList;
    private MyCustomAdapter mAdapter;
    private TCPClient mTcpClient;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        arrayList = new ArrayList<String>();

        final EditText editText = (EditText) findViewById(R.id.editText);
        Button send = (Button)findViewById(R.id.send_button);

        //relate the listView from java to the one created in xml
        mList = (ListView)findViewById(R.id.list);
        mAdapter = new MyCustomAdapter(this, arrayList);
        mList.setAdapter(mAdapter);

        // connect to the server
        new connectTask().execute("");

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String message = editText.getText().toString();

                //add the text in the arrayList
                arrayList.add("c: " + message);

                //sends the message to the server
                if (mTcpClient != null) {
                    mTcpClient.sendMessage(message);
                }

                //refresh the list
                mAdapter.notifyDataSetChanged();
                editText.setText("");
            }
        });

    }

    public class connectTask extends AsyncTask<String,String,TCPClient> {

        @Override
        protected TCPClient doInBackground(String... message) {

            //we create a TCPClient object and
            mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
                @Override
                //here the messageReceived method is implemented
                public void messageReceived(String message) {
                    //this method calls the onProgressUpdate
                    publishProgress(message);
                }
            });
            mTcpClient.run();

            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);

            //in the arrayList we add the messaged received from server
            arrayList.add(values[0]);
            // notify the adapter that the data set has changed. This means that new message received
            // from server was added to the list
            mAdapter.notifyDataSetChanged();
        }
    }
}

节点 JS 服务器

    var net = require('net');
var mysql = require('mysql');
var colorize = require('colorize');
var cconsole = colorize.console;

var clients = [];
var count = 0;

var messages = [];

function create_id()
{
        return count += 1;
}

setInterval(function()
{
        for(i = 0; i < clients.length; i++)
        {
                var client = clients[i];

                var params = {};
                params.type = "ping";

                if(client.socket.write(JSON.stringify(params)))
                {
                        console.log("ping send");
                }
                else
                {
                        clients.splice(i, 1);
                }
        }
}, 1000);

var server = net.createServer(function( socket )
{      
        cconsole.log("#red[Client connected to the server with ip: " + socket.remoteAddress+"]");

        socket.on("error",function(error)
        {
                console.log("error" + error);
        });

        socket.on("close",function()
        {
                cconsole.log("#red[Client has disconnected]");
        });

        socket.on("data",function(data)
        {        
                try
                {
                        var packet = JSON.parse(data);

                        if(packet.type == "register")
                        {
                                var client = [];

                                client.socket = socket;
                                client.clientID = create_id();
                                client.username = packet.username;

                                messages[packet.username] = [];

                                clients.push(client);

                                var params = {};

                                params.type = "register";
                                params.clientID = client.clientID;

                                socket.write(JSON.stringify(params));

                                console.log("Registered client : " + params.clientID);         
                        }

                        if(packet.type == "online")
                        {
                                var params = {};
                                var identifiers = [];

                                for(i = 0; i < clients.length; i++)
                                {

                                        identifiers.push(clients[i].clientID);
                                }

                                params.type = "online";
                                params.clients = identifiers;

                                socket.write(JSON.stringify(params));
                        }

                        if(packet.type == "message")
                        {
                                var client = packet.sender;
                                var recipient = packet.recipient

                                for(i = 0; i < clients.length; i++)
                                {
                                        if(clients[i].clientID.toString() == recipient.toString())
                                        {
                                                var params = {}

                                                params.type = "message";
                                                params.sender = packet.sender;
                                                params.recipient = packet.recipient;
                                                params.message = packet.message;

                                                clients[i].socket.write(JSON.stringify(params));

                                                console.log("Wrote message " + params.message + " from sender " + params.sender +  " to recipient " + recipient)
                                                return;
                                        }
                                }
                                        console.log("Recipient was not valid");                        
                        }
                }
                catch(e)
                {
                        cconsole.log(e.message);
                }
        });    
});

server.listen(8124,"<Server IP>", function()
{      
        //'listening' listener
        cconsole.log('Server is listening for incoming connections');
});
4

2 回答 2

0
while (mRun) {
                serverMessage = in.readLine();
                // check if you get a message here..

                if (serverMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(serverMessage);
                }
                serverMessage = null;

            }

尝试从评论中登录,看看你是否真的得到了什么

于 2013-10-01T16:37:29.113 回答
0

检查客户端和服务器程序的字节序。您的 Android 应用程序可能会以网络字节顺序 (Big Endian) 发送内容,而您的服务器期望它们以 Little Endian 格式发送。

如果是这种情况,您应该让您的两个客户端使用相同的字节顺序进行传输,例如通过使用以正确字节顺序进行处理的特定序列化程序。

于 2013-09-30T19:53:46.413 回答