12

我想将消息从 android 设备传输到桌面应用程序。我的问题是,我可以在不使用任何互联网连接的情况下将 android WiFi 设备与桌面 WiFi 设备连接起来。我想像蓝牙一样使用它。这可能吗?如果有可能,那么我该如何实施呢?

感谢和问候阿米特·塔珀

4

3 回答 3

15

这是 mreichert 建议的实现。当我遇到同样的问题时,我查找了这个,并认为我只是发布我的解决方案实现。这真的很简单。我还构建了一个 java 服务器,用于侦听来自 android 设备的传入请求(主要用于调试目的)。这是通过无线发送东西的代码:

import java.net.*;
import java.io.*;
import java.util.*;

import android.app.Activity;
import android.content.Context;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;


public class SMSConnection {
        /* The socket to the server */
    private Socket connection;

    /* Streams for reading and writing the socket */
    private BufferedReader fromServer;
    private DataOutputStream toServer;

    /* application context */
    Context mCtx;

    private static final String CRLF = "\r\n";

    /* Create an SMSConnection object. Create the socket and the 
       associated streams. Initialize SMS connection. */
    public SMSConnection(Context ctx) throws IOException {
        mCtx=ctx;
        this.open();
        /* may anticipate problems with readers being initialized before connection is opened? */
        fromServer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        toServer = new DataOutputStream(connection.getOutputStream());
    }

    public boolean open(String host, int port) {
        try {
            connection = new Socket(host, port);
            return true;
        } catch(IOException e) {
            Log.v("smswifi", "cannot open connection: " + e.toString());
        }
        return false;
    }

    /* Close the connection. */
    public void close() {
        try {
            connection.close();
        } catch (IOException e) {
            Log.v("smswifi","Unable to close connection: " + e.toString());
        }
    }

    /* Send an SMS command to the server. Check that the reply code
       is what is is supposed to be according to RFC 821. */
    public void sendCommand(String command) throws IOException {

        /* Write command to server. */
        this.toServer.writeBytes(command+this.CRLF);

        /* read reply */
        String reply = this.fromServer.readLine();
    }
}

这是连接类的基本框架。您只需实例化该类,然后在使用主机和端口创建的实例上调用 open(完成后不要忘记关闭连接),您可以根据自己的喜好更改 sendCommand 的主体。我在函数体中包含了一个读/写操作作为示例。

这是在远程计算机上运行服务器的代码,该服务器侦听连接并产生一个线程来处理每个请求。它可以轻松地与上述代码交互以进行调试(或任何用途)。

import java.io.*;
import java.net.*;
import java.util.*;

public final class smsd {
    ///////MEMBER VARIABLES
    ServerSocket server=null;
    Socket client=null;

    ///////MEMBER FUNCTIONS
    public boolean createSocket(int port) {
        try{
            server = new ServerSocket(port);
            } catch (IOException e) {
            System.out.println("Could not listen on port "+port);
            System.exit(-1);
        }
        return true;
    }

    public boolean listenSocket(){
        try{
            client = server.accept();
        } catch (IOException e) {
            System.out.println("Accept failed: ");
            System.exit(-1);
        }
        return true;
    }

    public static void main(String argv[]) throws Exception {
        //
        smsd mySock=new smsd();

        //establish the listen socket
        mySock.createSocket(3005);
        while(true) {
            if(mySock.listenSocket()) {
                //make new thread
                // Construct an object to process the SMS request message.
                SMSRequest request = new SMSRequest(mySock.client);

                // Create a new thread to process the request.
                Thread thread = new Thread(request);

                // Start the thread.
                thread.start();
            }
        }

        //process SMS service requests in an infinite loop

    }
///////////end class smsd/////////
}


final class SMSRequest implements Runnable {
    //
    final static String CRLF = "\r\n";
    Socket socket;

    // Constructor
    public SMSRequest(Socket socket) throws Exception 
    {
        this.socket = socket;
    }

    // Implement the run() method of the Runnable interface.
    public void run()
    {
        try {
            processRequest();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception
        {
           // Construct a 1K buffer to hold bytes on their way to the socket.
           byte[] buffer = new byte[1024];
           int bytes = 0;

           // Copy requested file into the socket's output stream.
           while((bytes = fis.read(buffer)) != -1 ) {
              os.write(buffer, 0, bytes);
           }
        }

    private void processRequest() throws Exception
    {
        // Get a reference to the socket's input and output streams.
        InputStream is = this.socket.getInputStream();
        DataOutputStream os = new DataOutputStream(this.socket.getOutputStream());

        // Set up input stream filters.
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        // Get the request line of the SMS request message.
        String requestLine = br.readLine();

        //print message to screen
        System.out.println(requestLine);

        //send a reply
        os.writeBytes("200");

        // Close streams and socket.
        os.close();
        br.close();
        socket.close();
    }
}

nb4 命名约定。

差点忘了。您需要在 AndroidManifest.xml 的标签内设置这些权限才能使用无线。

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
于 2010-12-09T08:20:57.500 回答
2

如果两个设备都使用相同的 wifi 网络并且可以相互 ping 通,这很容易实现。您可以在桌面上创建一个 Java 应用程序,它会创建一个ServerSocket. 然后,您可以Socket使用桌面的 IP 地址在您的 Android 应用程序中打开一个并通过OutputStream.

于 2010-11-24T11:20:03.393 回答
2

我相信 Amit 指的是让机器使用无线直接相互连接。

目前正在开发 Wifi-direct 规范,以允许接入点的即插即用设置。当前的问题是确保其中一台机器是其他机器可以建立连接的 AP。

我对这与 Ad-Hoc 网络的关系很感兴趣。我没有解决方案,但是我对这个问题也很感兴趣!(假设这是你的问题阿米特)。

于 2010-12-17T15:10:35.837 回答