【问题标题】:commumicating between windows app and android appwindows 应用程序和android 应用程序之间的通信
【发布时间】:2013-02-17 15:28:34
【问题描述】:

很抱歉,如果这是一个非常笼统的问题,但我不知道从哪里开始,所以我正在寻找想法。

我有一个 Windows 应用程序(乐谱编辑),目前正在将其移植到进展顺利的 Andriod。

我想添加一个功能,比在 windows 应用程序中创建的文档可以发送到用户的 android 平板电脑。我想知道,如果两者都在同一个本地网络上,我将如何在 Android 上编写某种侦听器,以便 Windows 端可以打开一个套接字或其他东西并向其发送数据。

谢谢

【问题讨论】:

    标签: android windows socket.io


    【解决方案1】:

    我认为直接通过本地网络发送文件并不是最好的方法。您很容易收到许多用户抱怨共享不起作用的问题。这主要是由于他们自己的网络配置问题。

    为什么不用像 DropBox 这样的服务来实现文件共享呢?

    DropBox 等服务提供简单的 API,可在应用程序中使用,以便将文件保存到远程文件夹,并从远程文件夹读取文件。

    这样,用户根本不必在同一个网络中。实现文件共享的大部分繁重工作将由专注于此的服务完成。

    加法:

    如果您不想为 DropBox 之类的单独服务要求帐户,请考虑以下方法:在您自己的 Web 服务器上实现一个非常简单的类似于 DropBox 的服务。制作一个简单的脚本,允许用户通过 HTTP 匿名上传文件到您的服务器。上传后,他们将收到此文件的 5 位数 ID,或者他们可以共享的其他链接。从第二个应用程序使用此 ID 或链接时,可以下载文件(再次通过 HTTP)。如果您在几个小时后自动从服务器中删除文件,您将不会用完空间。

    您可以用大约 20 行 PHP 代码来实现这样的服务。而且所需的应用程序代码非常简单(因为它只依赖于 HTTP)。如果您担心网络服务器的成本,您可以从每月 5 美元左右购买一台,甚至可以使用 Google App Engine 之类的免费服务(如果您的带宽和空间要求较低,则免费)。

    文件上传代码example。下载应该足够简单,可以单独完成。关于定期文件删除 - 显而易见的方法是 cron 但我认为没有它很容易管理。每当您接受新的上传(在 PHP 脚本中)时,检查所有下载并删除旧的。

    【讨论】:

    • 有趣的想法,但这需要使用来获得一个保管箱帐户对吧?另外,它是否在 Windows 端支持?看起来它只是 android 和 ios API。不过我会调查的。谢谢
    • 我很高兴收到关于否决票的评论,以便改进答案
    • 谢谢,无论如何我都想支持用户上传到我的网站。所以我会调查的。您碰巧没有任何示例代码可以做到这一点吗?顺便说一句,我不知道反对票是从哪里来的,当然不是我。
    • 这是一个例子:reecon.wordpress.com/2010/04/25/… PHP 脚本需要 9 行 ;)
    【解决方案2】:

    我写了一个小东西,这样我的 Windows 应用程序就可以找到在本地网络上运行的我的 android 应用程序的实例,就是这样。这是android代码第一

    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Arrays;
    
    import android.os.AsyncTask;
    import android.util.Log;
    
    public class TabSyncServer extends AsyncTask<Void, Void, Void> {
    
        ServerSocket mServerSocket = null;
        Socket mSocket = null;
        DataInputStream mDataInputStream = null;
        DataOutputStream mDataOutputStream = null;
    
        @Override
        protected void onPreExecute() {
    
            try {
                mServerSocket = new ServerSocket(2112);
                //System.out.println("Listening :2112");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        @Override
        protected Void doInBackground(Void... args) {
            byte[] bytebuf = new byte[1024];
            while (true) {
                try {
    
                    mSocket = mServerSocket.accept();
                    mDataInputStream = new DataInputStream(mSocket.getInputStream());
                    mDataOutputStream = new DataOutputStream(mSocket.getOutputStream());
                    Log.d("TabSyncServer", "ip: " + mSocket.getInetAddress());
                    mDataInputStream.read(bytebuf);
    
                    String str = new String(bytebuf, "UTF8");
                    Log.d("TabSyncServer", "message: " + str);
                    if(str.contains("Hello Android")) {
                        Log.d("TabSyncServer", "sending reply");
                        mDataOutputStream.writeBytes("Hello Windows");
                    }
    
                    // 
    
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (mSocket != null) {
                        try {
                            mSocket.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
    
                    if (mDataInputStream != null) {
                        try {
                            mDataInputStream.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
    
                    if (mDataOutputStream != null) {
                        try {
                            mDataOutputStream.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
    
        }
    
    }
    

    和windows MFC代码

        void CMainFrame::OnBrowseMobile() {
    
    
        CMobileSync* con = new CMobileSync();
        CString ipaddr_base;
        int my_last_digit;
        if(!con->getMyIP(ipaddr_base, my_last_digit)) {
            setMobilePath("Can't find local network");
            return;
        }
    
    
        for(int i=1 ; i<98 ; i++) {
            if(i==my_last_digit)
                continue;       // don;t check self
    
            CString ipaddr; ipaddr.Format("%s.%d", ipaddr_base, i);
            bool res = con->ConnectToHost(ipaddr);
            if(res) {
                res = con->SendMsg ("Hello Android");
    
                if(res) {
                    TRACE1("send ok %s\n",ipaddr.GetBuffer());
    #define RD_BUF_LEN 80
                    char buffer[RD_BUF_LEN];
                    if(con->ListenOnPortBlocking(buffer, RD_BUF_LEN)) {
                        if(strncmp(buffer, "Hello Windows", 12)==0) {
                            TRACE1("reply ok %s", buffer);
                            setMobilePath(ipaddr);
                            con->CloseConnection ();
                            return;
                        }
                    }
                } else {
                    TRACE("send FAILED\n");
                }
            }
            con->CloseConnection ();
        }
        setMobilePath("No TabTrax on local network");
    }
    
    #include "stdafx.h"
    #include <winsock.h>
    #include "MobileSync.h"
    
    #define TTPORT 2112
    bool CMobileSync::getMyIP(CString& ipaddr_front, int& ipaddr_lastdigit)
    {
        char szBuffer[1024];
    
        #ifdef WIN32
        WSADATA wsaData;
        WORD wVersionRequested = MAKEWORD(2, 0);
        if(::WSAStartup(wVersionRequested, &wsaData) != 0)
            return false;
        #endif
    
    
        if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)
        {
          #ifdef WIN32
          WSACleanup();
          #endif
          return false;
        }
    
        struct hostent *host = gethostbyname(szBuffer);
        if(host == NULL)
        {
          #ifdef WIN32
          WSACleanup();
          #endif
          return false;
        }
    
        //Obtain the computer's IP
        unsigned char b1, b2, b3, b4;
        b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
        b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
        b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
        b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;
    
        ipaddr_front.Format("%d.%d.%d", b1, b2, b3);
        ipaddr_lastdigit = b4;
        #ifdef WIN32
        WSACleanup();
        #endif
        return true;
    }
    
    //CONNECTTOHOST – Connects to a remote host
    bool CMobileSync::ConnectToHost(const char* IPAddress)
    {
        //Start up Winsock…
        WSADATA wsadata;
    
        int error = WSAStartup(0x0202, &wsadata);
    
        //Did something happen?
        if (error)
            return false;
    
        //Did we get the right Winsock version?
        if (wsadata.wVersion != 0x0202)
        {
            WSACleanup(); //Clean up Winsock
            return false;
        }
    
        //Fill out the information needed to initialize a socket…
        SOCKADDR_IN target; //Socket address information
    
        target.sin_family = AF_INET; // address family Internet
        target.sin_port = htons (TTPORT); //Port to connect on
        target.sin_addr.s_addr = inet_addr (IPAddress); //Target IP
    
        mSocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); //Create socket
        if (mSocket == INVALID_SOCKET)
        {
            return false; //Couldn't create the socket
        }  
    
        //Try connecting...
    
        if (connect(mSocket, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR)
        {
            return false; //Couldn't connect
        }
    
        return true; //Success
    }
    
    //CLOSECONNECTION – shuts down the socket and closes any connection on it
    void CMobileSync::CloseConnection ()
    {
        //Close the socket if it exists
        if (mSocket)
            closesocket(mSocket);
        mSocket=0;
    
        WSACleanup(); //Clean up Winsock
    }
    
    int CMobileSync::SendMsg (char* szpText, int buflen)
    {
        if(buflen==0)
            buflen = strlen(szpText);
        int ret = send(mSocket, szpText, buflen, 0);
        TRACE1("CMobileSync::SendMsg sent %d bytes\n", ret);
        return ret;
    }
    
    WSADATA w;
    
    //LISTENONPORT – Listens on a specified port for incoming connections 
    //or data
    bool CMobileSync::ListenOnPortBlocking(char* buffer, int buflen)
    {
        //Now we can start listening (allowing as many connections as possible to  
        //be made at the same time using SOMAXCONN). You could specify any 
        //integer value equal to or lesser than SOMAXCONN instead for custom 
        //purposes). The function will not //return until a connection request is 
        //made
        // listen(s, SOMAXCONN);
    
        memset(buffer, 0, sizeof(buffer)); //Clear the buffer
    
        int iTimeout = 1600;
        setsockopt( mSocket,  SOL_SOCKET, SO_RCVTIMEO, (const char *)&iTimeout, sizeof(iTimeout));
    
        //Put the incoming text into our buffer
        int ret = recv (mSocket, buffer, buflen-1, 0); 
    
        //Don't forget to clean up with CloseConnection()!
    
        if(ret != SOCKET_ERROR)
            return true;
    
        int err = WSAGetLastError();
        return false;
    }
    

    它没有经过广泛的测试,但它正在运行

    这可能对某人有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-25
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多