的Node.js和WebSocket的Andr​​oid中的EclipseWebSocket、js、Node、Eclipse

2023-09-04 12:27:11 作者:我用娃娃做代替。

感谢您寻找到我的问题。

Thanks for looking into my question.

我在android开发的初学者,目前我正在试图让聊天应用程序,它使用套接字和节点JS。

I am a beginner in android development and currently i am trying to make chat app which uses socket and node js.

我用一个图书馆从github上即 https://github.com/Gottox/socket .IO-Java的客户端,并能够将消息发送到我的服务器和我能够收回的消息以及在new_client_message,这是显示在下面的logcat中的形象。

I used a library from github i.e https://github.com/Gottox/socket.io-java-client and was able to send message to my server and i was able to receive back message as well under "new_client_message" which is shown in the logcat image below.

我面临的问题是,我无法弄清楚的方式从服务器获取的消息在列表视图中显示它。这将是巨大的,如果有人可以帮助我。在此先感谢

The problem i am facing is that i cannot figure out the way to get the messages from the server to display it in a list view. It would be great if anyone could help me out. Thanks in advance

我的LogCat中:

My LogCat:

Node.js的code:

Node.js Code:

var socket = require('socket.io');
var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

var io = socket.listen(server);

var users = {};
var clients = {};

io.sockets.on( 'connection', function(socket) {
console.log("New client !");
var socket_id = socket.id;
var hs = socket.handshake;
//store user with socket id
if(hs.query.user_id !== undefined){
    users[hs.query.user_id] = socket.id; // connected user with its     socket.id

}

clients[socket.id] = socket; // add the client data to the hash

socket.on('disconnect', function () {
    delete clients[socket.id]; // remove the client from the array
    delete users[hs.query.username]; // remove connected user & socket.id
});

socket
    .on('new_message', function(data){
        clients[users['admin']].emit('new_message', {'original_data':data,'socket_id': socket_id } );
    })
    .on('new_client_message', function(data){
        console.log(data);
        clients[data.socket_id].emit('new_client_message', data.message);
    })
;

});

server.listen(3030);

和这里是我的code:

And here is my code:

socket = null;
    try {
        socket = new SocketIO("http://xxx.xxx.xx.xx:3030/");
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    socket.connect(new IOCallback() {
        @Override
        public void onMessage(JSONObject json, IOAcknowledge ack) {
            try {
                System.out.println("Server said:" + json.toString(2));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onMessage(String data, IOAcknowledge ack) {
            System.out.println("Server said: " + data);

        }

        @Override
        public void onError(SocketIOException socketIOException) {
            System.out.println("an Error occured");
            socketIOException.printStackTrace();
        }

        @Override
        public void onDisconnect() {
            System.out.println("Connection terminated.");
        }

        @Override
        public void onConnect() {
            System.out.println("Connection established");
        }

      //here I was trying to get the message from the server, convert into string and 
      //display in list view(thats when the error displayed)

        @Override
        public void on(String event, IOAcknowledge ack, Object... args) {
            System.out.println("Server triggered event '" + event + "'");
            System.out.println("senrver ack" + ack);
            System.out.println("server said this " + args[0]);

            rohan = args[0].toString();


            mListData.add(rohan);
            //mListData.add(args[0].toString());

        }


    });

    //mListData.add(rohan);

  //sending the message from the app when onclick to the server which is sucessful

    send.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub


            // This line is cached until the connection is establisched.
            //socket.send("new_message");



            chat = messag.getText().toString();

            karan = client_email+";"+chat;

         // This line is cached until the connection is establisched.
            socket.emit("new_message", karan);
            click();




        }

        private void click() {
            // TODO Auto-generated method stub
            //getting the username
            name = getIntent().getExtras().getString("name");
            String output = name.substring(0,1).toUpperCase() + name.substring(1);


            // converting the TextView message to string
            msg = messag.getText().toString();

            // combining the username and the text view
            messag.setText(output +" " + ":" + " " + msg);

            //showing the final combination in the listview
            mListData.addAll(messag.getText().toString());

            messag.setText("");

            //when the list view is updated with data, then it goes to that position
            lvList.setSelection(mListData.getCount() -1);
            post();

        }

请指导我应该从哪里进一步增加code到diplay从列表视图中的node.js服务器的消息。我相信,我在做一些错误,我将AP preciate如果有人可以纠正我。 很多的感谢!

Please guide me where should i add further code to diplay the message from the node.js server in the listview. I am sure that i am making some mistake and i would appreciate if someone could correct me. Much thanks !

推荐答案

海兰卡兰..你会以正确的方式配合。这是唯一缺少的就是一小段code。这里的错误是您在工作线程设置适配器。您可以更新只能从主线程的意见。 你必须移动该更新UI到主线程的后台任务的所述部分。 只需更换code的:

Hy Karan.. you are going in the right way mate. The only thing that is missing is the small snippet of code. Error here is that you set adapter in working thread. You can update views only from main thread. You have to move the portion of the background task that updates the ui onto the main thread. Just replace the code on:

@Override
            public void on(String event, IOAcknowledge ack, Object... args)

@Override
            public void on(String event, IOAcknowledge ack, Object... args) {
                // TODO Auto-generated method stub
                if(event.equals("new_client_message")){
                    Log.v("SocketIO", "new_client_message" + " " + args[0]);
                    rohan = args[0].toString();
                    System.out.println("admin" + " : " + " " + rohan);

                    runOnUiThread(new Runnable(){

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            mListData.add("Admin" + " : " + " " + rohan);
                            mListData.notifyDataSetChanged();
                            lvList.setSelection(mListData.getCount() -1);

                        }

                    });
                }

在这里new_client_message是从服务器触发..只是取代你的。 例如,在你的情况下new_message为您的应用程序服务器触发。对不起,我不是一个专业的词,但我希望这将有助于。 干杯

here "new_client_message" is trigger from the server.. just replace with yours. For example in you case "new_message" is the trigger from your app to the server. Sorry for not a professional word but i hope it will help. Cheers