Android中搭建AndServer服务器的示例代码
时间: 2024-03-18 12:14:22 浏览: 27
可以参考以下示例代码:
```java
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;
import com.yanzhenjie.andserver.Server.ServerListener;
import com.yanzhenjie.andserver.http.HttpRequest;
import com.yanzhenjie.andserver.http.HttpResponse;
import com.yanzhenjie.andserver.util.IOUtils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class AndServerSample {
public static void main(String[] args) {
// 创建AndServer
Server server = AndServer.serverBuilder()
.port(8080)
.listener(new ServerListener() {
@Override
public void onStarted() {
System.out.println("Server started.");
}
@Override
public void onStopped() {
System.out.println("Server stopped.");
}
@Override
public void onException(Exception e) {
System.err.println("Server exception: " + e.getMessage());
}
})
.build();
// 添加处理器
server.addHandler("/hello", new HttpHandler() {
@Override
public void handle(HttpRequest request, HttpResponse response) {
response.setHeader("Content-Type", "text/plain");
response.setBody("Hello, AndServer!");
// send response
response.commit();
}
});
server.addHandler("/file", new HttpHandler() {
@Override
public void handle(HttpRequest request, HttpResponse response) {
FileInputStream fis = null;
try {
fis = new FileInputStream("test.txt");
byte[] bytes = IOUtils.toByteArray(fis);
response.setBody(bytes);
response.commit();
} catch (FileNotFoundException e) {
response.setStatusCode(404);
response.commit();
} catch (IOException e) {
response.setStatusCode(500);
response.commit();
} finally {
IOUtils.closeQuietly(fis);
}
}
});
// 启动服务器
server.startup();
}
}
```
在该示例代码中,AndServer监听本地8080端口,然后添加了两个处理器,一个是用来返回“Hello, AndServer!”字符串,另一个是用来读取文件并返回文件内容。最后启动服务器。如果需要退出服务器,可以通过`server.shutdown()`方法关闭服务器。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)