Android使用WIFI连接到WIFI的连通性

12

我想把Android设备上的消息传输到桌面应用程序中。我的问题是,我能否在不使用互联网连接的情况下将Android WiFi设备与桌面WiFi设备相连接,就像使用蓝牙一样。这是否可能?如果可能,那么如何实现呢?

谢谢和问候, Amit Thaper


那个问题很难读,请检查您的格式! - Gareth Davidson
3个回答

15

这是mreichelt建议的一个实现。我在遇到相同问题时查找了此内容,并决定发布解决方案的实现方式。它非常简单。我还建立了一个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();
    }
}

nb4namingconventions.

几乎忘记了。您需要在AndroidManifest.xml文件中的<manifest>标签内设置这些权限,才能使用无线功能。

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

2
如果两个设备都在使用相同的WiFi网络并且能够互相ping通,那么这就很容易实现。你可以在桌面上创建一个Java应用程序,它创建一个ServerSocket。然后,在Android应用程序中使用桌面的IP地址打开一个Socket,并通过OutputStream发送数据。

2
我认为Amit指的是使用无线连接直接将机器连接在一起的方式。
目前正在开发Wifi-direct规范以实现接入点的即插即用设置。目前的问题是确保其中一台计算机是其他计算机可以建立连接的接入点。
我对这与Ad-Hoc网络的关系很感兴趣,但我没有解决方案。不过我也非常关注这个问题!(假设这是您的问题,Amit)。

是的,我想按照Eric定义的方式进行连接。举个例子来澄清,答案是手机蓝牙。我想要通过WiFi将两个设备配对,就像使用蓝牙一样,而不使用任何路由器。 - Amit Thaper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接