5

我现在在这个问题上闲逛了一段时间。我通过接收端的套接字将数据从设备发送到设备我必须将此数据从套接字发送到设备本身。localhost/127.0.0.1/10.0.0.2或 WiFi 地址不起作用。

如何将数据从套接字发送到localhost:port设备?

try
{
    Socket socket = new Socket(InetAddress.getLocalHost(), 1500);
    InputStream is = s.getInputStream();
    OutputStream os = socket.getOutputStream();
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    int len = 0;
    while ((len = is.read(buffer)) > 0)
    {
        if(is.available() > 1024){
            os.write(buffer);
        Log.i(TAG, "localSocket writing: " + buffer.length);
        }


        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            Log.e(TAG, "LocalSocketThread" + e.toString());
        }
    }
}

和我的清单权限:

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.CAMERA" /> 
<uses-permission android:name="android.permission.STORAGE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
4

2 回答 2

0

尝试将 null 发送到地址字段:

Socket socket = new Socket(null, 1500);
于 2014-06-20T13:08:36.307 回答
-1

看到你的代码,因为它是写的,没有意义,你从套接字读取并立即测试可用()。您只是从中读取,所以很可能它会返回 0。

while ((len = is.read(buffer)) > 0)
{
   // this is what makes no sense
   if (is.available() > 1024) os.write(buffer);
   // what you probably want to do is
   //  Even this test is not necessary because you already test in the while loop
   if (len > 0) 
   {
      os.write(buffer, 0, len);
      Log.i(TAG, "localSocket writing: " + len);
   }
于 2013-05-14T09:44:06.233 回答