在扑朔迷离中实现客户端服务器应用程序时出现问题

时间:2020-05-20 08:19:06

标签: go flutter websocket server client

我正在尝试实现websocket客户端服务器应用程序,如果我从客户端发送短信,则该短信应显示在其他客户端上。目前,我可以通过同一客户端上的服务器进行回显,但是数据不会发送到其他客户端。我想念什么?

这是我的golang服务器

package main

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

var upgrader = websocket.Upgrader{}

func connectionHandler(w http.ResponseWriter, r *http.Request){
    conn, err := upgrader.Upgrade(w,r,nil)
    if err != nil {
        log.Println(err)
        return
    }
    fmt.Println(r)
    for{
            messagetype, p, err := conn.ReadMessage()
            log.Println(string(p))
            if err != nil {
                log.Println("READ MESSSAGE ERROR")
                log.Println(err)
                return
            }

            if err = conn.WriteMessage(messagetype, p); err != nil {
                log.Println("WRITE MESSAGE ERROR")
                log.Println(err)
                return
            }
    }
}

func main(){

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

    mux.HandleFunc("/test", connectionHandler)

    log.Fatal(http.ListenAndServe("0.0.0.0:6969", mux))

}

我的客户代码扑朔迷离

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

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

class Root extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: UserInput(),
    );
  }
}

class UserInput extends StatefulWidget {
  @override
  _UserInputState createState() => _UserInputState();
}

class _UserInputState extends State<UserInput> {
  TextEditingController myController;
  String value;
  WebSocketChannel channel;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    myController = TextEditingController();
    channel = IOWebSocketChannel.connect('ws://192.168.225.220:6969/test');
//    channel.stream.listen((event) {return event;});
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: myController,
              decoration: InputDecoration(
                labelText: "Send to WebSocket",
              ),
            ),
            RaisedButton(
              child: Text("Submit"),
              onPressed: (){
                setState(() {
                  value = myController.text;
                  sendMessage();
                });
              },
            ),
            SizedBox(height: 20,),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                value==null ? Text(" ") : Text(value),
                StreamBuilder(
                  stream: channel.stream,
                  builder: (context, snapshot) {
                    if(snapshot.hasData)
                      return Text(snapshot.data.toString());
                    return Text("Waiting for data");
                  },
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}

0 个答案:

没有答案