我正在编写一个需要在本地与其他手机通信的应用。 (在同一个wifi网络中)在this教程之后有一个在端口8202上运行的非常简单的apache webserver,但是我想知道发出请求的客户端的本地 IP。
Webserver类:
public class WebServer {
public static boolean RUNNING = false;
public static int serverPort = 8202;
private Context context = null;
private BasicHttpProcessor httpproc = null;
private BasicHttpContext httpContext = null;
private HttpService httpService = null;
private HttpRequestHandlerRegistry registry = null;
public WebServer(Context context) {
this.setContext(context);
httpproc = new BasicHttpProcessor();
httpContext = new BasicHttpContext();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
registry = new HttpRequestHandlerRegistry();
registry.register("*", new CommandHandler(context));
httpService.setHandlerResolver(registry);
}
private ServerSocket serverSocket;
public void runServer() {
try {
serverSocket = new ServerSocket(serverPort);
serverSocket.setReuseAddress(true);
while (RUNNING) {
try {
final Socket socket = serverSocket.accept();
DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection();
serverConnection.bind(socket, new BasicHttpParams());
httpService.handleRequest(serverConnection, httpContext);
serverConnection.shutdown();
} catch (IOException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
}
}
serverSocket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
RUNNING = false;
}
public synchronized void startServer() {
RUNNING = true;
Log.d("SEVRER", "running");
runServer();
}
public synchronized void stopServer() {
RUNNING = false;
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d("SEVRER", "stopping");
}
public void setContext(Context context) {
this.context = context;
}
public Context getContext() {
return context;
}
CommandHandler类:
public class CommandHandler implements HttpRequestHandler {
private Context context = null;
public CommandHandler(Context context) {
this.context = context;
}
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
HttpEntity entity = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("output");
writer.flush();
}
});
response.setHeader("Content-Type", "text/html");
response.setEntity(entity);
}
public Context getContext() {
return context;
}
我是否缺少某些东西,或者我应该使用其他东西来运行服务器?
答案 0 :(得分:0)
您可以使用
socket.getInetAddress().getHostAddress();
在runServer()方法中。