将套接字连接到设备上的本地地址

时间:2013-02-28 14:03:14

标签: android sockets localhost

我现在暂时搁浅这个问题了。我通过接收端的套接字从设备向设备发送数据我必须将这些数据从套接字发送到设备本身。 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"/>

2 个答案:

答案 0 :(得分:0)

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

Socket socket = new Socket(null, 1500);

答案 1 :(得分:-1)

看到你的代码,因为它是写的,没有意义,你从套接字读取并立即测试available()。你只需要阅读它,所以很可能会返回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);
   }