我为Android写了一个简单的HTTP-Proxy,它正在侦听设备的外部IP地址和一个特定的端口(例如192.168.1.20:8080)。
我可以从设备本身访问IP /端口 - 但是在运行循环中永远不会接受来自外部设备的任何尝试。
简化代码如下所示:
public class MainActivity extends AppCompatActivity implements Runnable {
private ServerSocket socket;
private int port = 8080;
private Thread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Log.v("TAG", "http://"+ip+":"+port);
try {
Log.v("TAG", InetAddress.getByName(ip).toString());
socket = new ServerSocket(port, 5, InetAddress.getByName(ip));
socket.setSoTimeout(5000);
thread = new Thread(this);
thread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
Socket client = socket.accept();
// Never reaches this line if connected externally
Log.d("TAG", "client connected");
} catch (SocketTimeoutException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我还在AndroidManifest.xml中添加了权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
但仍然没有运气。那里有谁可以提供建议?
THX。