gpt4 book ai didi

go - 无法将 websocket 数据从 flutter 应用程序发送到服务器

转载 作者:行者123 更新时间:2023-12-01 22:23:21 32 4
gpt4 key购买 nike

我正在尝试使用 flutter 应用程序客户端和 go server 创建服务器-客户端架构。
目前我正在尝试从 flutter 应用程序发送文本输入,以使用 Websockets 在服务器端读取和打印它。

我已经成功测试了我的 flutter 应用程序以从 https://www.websocket.org/echo 回显.
要连接到我的本地服务器,这里是相关位

用于连接服务器

  final channel = IOWebSocketChannel.connect('ws://localhost:8080/test');


当 onPressed 发送用户输入的数据时,调用 sendMessage();
void sendMessage(){
if(myController.text.isNotEmpty){
channel.sink.add(myController.text);
}
}

我已阅读 https://godoc.org/github.com/gorilla/websocket docs 和其他博客了解 mux、handlefunc 和 listenandserve 功能,但我无法发送数据。

这是我的 Go 服务器:
package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
}

func connectionHandler(w http.ResponseWriter, r *http.Request){
conn, err := upgrader.Upgrade(w,r,nil)
if err != nil {
log.Println(err)
return
}

for{
messageType, p, err := conn.NextReader()
fmt.Println(p)
fmt.Println(messageType)
if err != nil {
log.Println(err)
return
}
}

}

func main(){

mux := http.NewServeMux()
fmt.Printf("Connecting to server \n")

mux.HandleFunc("/test", connectionHandler)

log.Fatal(http.ListenAndServe(":8080", mux))

}

编辑:
添加了 Flutter 客户端代码。
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/html.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/status.dart' as status;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shopping',
initialRoute: 'home',
theme: ThemeData(
primarySwatch: Colors.lightBlue,
),
routes: <String, WidgetBuilder>{
'home': (BuildContext context) => HomePage(title: "Home"),
'/shoppingpage': (BuildContext context) => ShoppingCart(title: "Shopping Cart Page"),
},

);
}
}

class HomePage extends StatelessWidget {
HomePage({Key key, this.title}) : super(key:key);
final String title;
final channel = IOWebSocketChannel.connect('ws://localhost:8080/test');
TextEditingController myController = TextEditingController();
final GlobalKey<ScaffoldState> _scaffoldkey = new GlobalKey<ScaffoldState>();

@override
void dispose(){
myController.dispose();
channel.sink.close();
}

@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldkey,
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
FlatButton(
onPressed: (){
return (Navigator.of(context).pushNamed('/shoppingpage'));
},
child: Text('Start Game'),
color: Colors.blue,
splashColor: Colors.green,

),

TextField(
controller: myController,

),

FloatingActionButton(
onPressed: (){
sendMessage();
_scaffoldkey.currentState.showSnackBar(SnackBar(
content: Text('Sent'),
));
},
child: Icon(Icons.send),
),

StreamBuilder(
stream: channel.stream,
builder: (context, snapshot){
return snapshot.hasData ? Text(snapshot.data.toString(),
) : CircularProgressIndicator();
}
),
],
),
);
}

void sendMessage(){
if(myController.text.isNotEmpty){
channel.sink.add(myController.text);
}
}

}



class ShoppingCart extends StatelessWidget {
ShoppingCart({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: BackButton(onPressed: (){
return Navigator.pop(context);
}),
),
);
}
}

最佳答案

如果您在 PC 上运行 Go 服务器,但在移动/模拟器上运行 Flutter 应用程序,那么 localhost不起作用(它会指向手机/模拟器,而不是 PC)。

您需要使用从电话解析到 PC 的 IP 地址/主机名,并确保 Go 服务器绑定(bind)到网络可访问的 IP(并且没有防火墙)。

关于go - 无法将 websocket 数据从 flutter 应用程序发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61544989/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com