使用dart创建Http服务器时出现连接拒绝错误



我使用Plane dart创建了一个服务器,并尝试使用HTTPget侦听响应。当我在浏览器中ping I/P时,我可以访问响应,但当我试图在演示应用程序中访问时,我会收到错误

SocketException:操作系统错误:连接被拒绝,错误号=111,地址=127.0.0.1,端口=36000

我的服务器代码如下:

class ServerUtilities {
static Directory _appDirectory;
static HttpServer _server;
static File _file;
ServerUtilities._();
static ServerUtilities _obj;
static ServerUtilities instance() {
if (_obj == null) _obj = ServerUtilities._();
return _obj;
}
Future<Directory> setAppDirectory() async {
return await getApplicationDocumentsDirectory();
}
void initializeServer(String address, int port) async {
_appDirectory = await setAppDirectory();
print(_appDirectory.path);
_file = File('${_appDirectory.path}/sample.txt');
_file.writeAsString("Hiii ", mode: FileMode.append);
_server = await HttpServer.bind(address, port);
print("Server initialized - " + address + ":" + port.toString());
await for (var req in _server) {
if (await _file.exists()) {
print("file exist");
// req.response.headers.contentType = ContentType.text;
await _file.openRead().pipe(req.response);
}
}
}
void stopServer() async {
await _server.close().catchError(
(e) {
print(e);
},
).then(
(value) => {
print("Server stopped "),
},
);
}
}

服务器已经初始化,一切都很好,可以在我的移动浏览器中打开提供的IP,它运行得很好,但当我尝试使用Http.get时,我出现了上述错误。

这是我的主菜。

void main() async {
WidgetsFlutterBinding.ensureInitialized();
ServerUtilities.instance().initializeServer('127.0.0.1', 8010);
runApp(
MaterialApp(
home: MyApp(),
),
);
}

这就是我试图访问的方式,我得到了上面指定的错误。

FutureBuilder(
future: http.get("http://127.0.0.1:8010"),
builder: (context, data) {
if (data.hasData)
return Text(
data.toString(),
style: TextStyle(fontSize: 20),
);
else if (data.hasError) {
print(data.error);
return Text(
data.error.toString(),
style: TextStyle(fontSize: 20),
);
} else
return Text(
"No data",
style: TextStyle(fontSize: 20),
);
}),

服务器未运行时会出现此错误。因此,请检查initializeServer方法是否正常工作。

最新更新