在Android两个应用程序之间的Socket通信 [英] Socket communication between two apps on Android

查看:310
本文介绍了在Android两个应用程序之间的Socket通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有巨大的问题,与我的Andr​​oid应用程序,我想请你帮忙。

I have got huge problem with my Android app and I would like to ask you for help.

我目前正在写使用套接字的Andr​​oid Clietn - 服务器应用程序。我发现很多在互联网上tutorils,并从他们那里我创建的基础知识为我的项目。然而,所有教程仅适用于一个消息发送,这一切。我需要发更多的人,所以我一直在试图对其进行修改。

I am currently writing Android Clietn-Server app using sockets. I have found lots of tutorils on the Internet and from them I have created basics for my project. However, all tutorials are only for one message send and that's all. I need to send more of them so I've been trying to modify it.

该负责服务器和客户机code片段。其余并不重要,此时

This are code fragments responsible for server and client. The rest is not important at this time.

服务器:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        serverStatus = (TextView) findViewById(R.id.server_status);
        recivedMsg = (TextView)findViewById(R.id.rec_msg);

        SERVERIP = getLocalIpAddress();

        Thread fst = new Thread(new ServerThread());
        fst.start();
    }

    public class ServerThread implements Runnable {

        public void run() {
            try {
                if (SERVERIP != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus.setText("Listening on IP: " + SERVERIP);
                        }
                    });
                    serverSocket = new ServerSocket(SERVERPORT);
                    while (true) {
                        // listen for incoming clients
                        Socket client = serverSocket.accept();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                serverStatus.setText("Connected." + System.getProperty("line.separator"));
                            }
                        });

                        try {
                            line = null;
                            while (connected) {
                                BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                                if((line = in.readLine())!=null)
                                {
                                    Log.d("ServerActivity", line);
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if(recivedMsg.equals("CLOSE"))
                                            {
                                                recivedMsg.append("CLOSE socket");
                                                connected = false;
                                            }
                                            else
                                            {
                                                recivedMsg.append("MSG: " + line + System.getProperty("line.separator"));
                                            }
                                            // do whatever you want to the front end
                                            // this is where you can be creative
                                        }
                                    });
                                }
                                else
                                {
                                    recivedMsg.append("empty" + System.getProperty("line.separator"));
                                }
                            }
                            break;
                        } catch (Exception e) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
                                }
                            });
                            e.printStackTrace();
                        }
                    }
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus.setText("Couldn't detect internet connection.");
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Error");
                    }
                });
                e.printStackTrace();
            }
        }
    }

客户端

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

        serverIp = (EditText) findViewById(R.id.server_ip);
        connectPhones = (Button) findViewById(R.id.connect_phones);

        sendField = (EditText) findViewById(R.id.send_field);
        sendMsg = (Button) findViewById(R.id.msg_send);

        connectPhones.setOnClickListener(connectListener);
        sendMsg.setOnClickListener(sendMessage);
    }

    @Override
    protected void onStop() {
         super.onStop();
         try {
                 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                 //send output msg
                 String outMsg = "CLOSE"; 
                 out.write(outMsg);
                 out.flush();
                 // make sure you close the socket upon exiting
                 s.close();
         } catch (IOException e) {
                 e.printStackTrace();
         }
    }

    private OnClickListener connectListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            serverIpAddress = serverIp.getText().toString();
            runTcpConnection();
            sendMessageToServer("Msg");
        }
    };

    private OnClickListener sendMessage = new OnClickListener() {

        @Override
        public void onClick(View v) {
            sendMessageToServer(sendField.getText().toString());
        }
    };

    private void runTcpConnection() {
        try {
            s = new Socket(serverIpAddress, SERVERPORT);
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            //send output msg
            String outMsg = "TCP connecting to " + SERVERPORT + System.getProperty("line.separator"); 
            out.write(outMsg);
            out.flush();
            Log.i("TcpClient", "sent: " + outMsg);
            SystemClock.sleep(10);
            s.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    public void sendMessageToServer(String str) {
        try {
                    s = new Socket(serverIpAddress, SERVERPORT);
                    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                    //send output msg
                    String outMsg = str + System.getProperty("line.separator"); 
                    out.write(outMsg);
                    out.flush();
                    Log.i("TcpClient", "sent: " + outMsg);
                    s.close();
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d("", "hello222");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d("", "hello4333");
                }

            }

目前设备连接正确。此外,他们发送的第一个连接消息(那些 OnClickListener connectListener )。 的问题是,当我试图通过发送另一个消息 sendMessageToServer 这是不可能的。这些消息只显示后,客户端活动被销毁。

For now devices connect correctly. Moreover They are sending the first connection messages (those in OnClickListener connectListener). The problem is that when I am trying to send another message using sendMessageToServer it is impossible. Those messages shows only after client activity is destroyed.

很有意思的是,如果没有 SystemClock.sleep(10); 监听器 runTcpConnection()行为怪异。只有已连接。在服务器上显示。

Very interesting is that without SystemClock.sleep(10); listener runTcpConnection() behave strange. Only 'Connected.' displays on server.

谁可以告诉我,我必须做的,能够正常发送邮件?

Can someone tell me what I have to do to be able to send messages normally?

编辑: 这是我找到的东西:

This are things that I have found:

  • 如果我在的连接发送更多的消息比一切都是空(NULL),第二个连接错误显示后 - 请重新连接手机
  • 如果我在 sendMessageToServer 的连接发送更多的消息,而无需S.CLOSE行只有一个消息被通过。后不显示错误。
  • 在该消息的形式 runTcpConnection 总是显示(除非在这个函数是没有SystemClock.sleep(10))
  • If I am at the connection sending more messages than all are empty (null) and after the second one connection error shows - please reconnect phones
  • If I am at the connection sending more messages without s.close line in sendMessageToServer only one message is passing through. No error is displayed after it.
  • The message form runTcpConnection shows always (except when in this function is no SystemClock.sleep(10))

希望这将帮助别人来诊断我的错误。

Hope it will help someone to diagnose my error.

推荐答案

据我看到的,你创建一个用户时点击按钮,发送新的插座,对不对?
我建议你应该初始化它只有一次,当用户点击连接,那么你在发送单击事件使用它(因为这是TCP,你会断开连接到服务器,如果你创建套接字的新实例)
所以,你应该删除的这些行中的 sendMessageToServer 的:

As I see, you create a new socket whenever user click button send, right?
I recommend you should init it only one time when user click connect, then you use it in send click event ( because this is TCP, you will disconnect to server if you create new instance of socket)
So, you should remove these lines in sendMessageToServer :

s = new Socket(serverIpAddress, SERVERPORT);
s.close();

和此行的 runTcpConnection

s.close();

插座应该关闭,只要你不想与服务器通信(的onStop就是一个例子,或者更改活动...)
你也应该创建BufferedWriter将只有一个实例了。
希望这有助于。

Socket should close whenever you don't want communicate with the server (onstop is an example, or when change activity...)
Also you should create only one instance of BufferedWriter too.
Hope this help.

这篇关于在Android两个应用程序之间的Socket通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆