Flutter Client Olacak Şekilde Pythondan Server Yazma

Merhabalar. Flutter’dan online bir uygulama yazmaya çalışıyorum ama python sunucusuna veri gönderemiyorum.

Flutter client kodu:

//import 'dart:developer';      enes yavuz bi tane program kullanıodu c için ona sor
//import 'dart:io';
//import 'package:dart_eval/dart_eval.dart';
import 'dart:convert';
import 'dart:developer';
import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/status.dart' as status;
import 'package:web_socket_channel/web_socket_channel.dart';

String HOST = 'localhost';
int PORT = 4609;

void main() async {
  // Dart client
  runApp(
    const MaterialApp(
      home: MainPage(),
    ),
  );
}
//class Connection(){

//}

bool logedIn = false;
String username = 'null';
String passWord = 'null';

int _x = 0;
int _bakiye = 0;
int _indexCurrent = 0;
String inputUsername = 'null';
String inputPassWord = 'null';
String appBarTopicYemek = 'Restorantlar';

class LogInPage extends StatefulWidget {
  const LogInPage({super.key});

  @override
  State<LogInPage> createState() => _LogInPageState();
}

//giriş yapma sayfası

class _LogInPageState extends State<LogInPage> {
  final _textControllerPassword = TextEditingController();
  final _textControllerUsername = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          leading: BackButton(
            onPressed: () {
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => const MainPage()));
            },
          ),
          centerTitle: true,
          title: const Text('Giriş Yap'),
          backgroundColor: const Color.fromARGB(255, 77, 222, 255),
        ),
        body: Center(
          child: SizedBox(
            width: 300,
            height: double.infinity,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                const Text('\n\n\n\n'),
                SizedBox(
                  width: 300,
                  child: TextField(
                    controller: _textControllerUsername,
                    decoration: InputDecoration(
                      hintText: 'Kullanıcı Adı',
                      border: const OutlineInputBorder(),
                      suffixIcon: IconButton(
                        onPressed: () {
                          _textControllerUsername.clear();
                        },
                        icon: const Icon(Icons.clear),
                      ),
                    ),
                    maxLength: 16,
                  ),
                ),
                const Text('\n', style: TextStyle(fontSize: 5)),
                SizedBox(
                  width: 300,
                  child: TextField(
                    obscureText: true,
                    controller: _textControllerPassword,
                    decoration: InputDecoration(
                      hintText: 'Şifre',
                      border: const OutlineInputBorder(),
                      suffixIcon: IconButton(
                        onPressed: () {
                          _textControllerPassword.clear();
                        },
                        icon: const Icon(Icons.clear),
                      ),
                    ),
                  ),
                ),
                const Text('\n'),
                Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                  ElevatedButton(
                    onPressed: () {
                      inputPassWord = _textControllerPassword.text;
                      inputUsername = _textControllerUsername.text;
                      // TODO: make a password correction system

                      // TODO: sent and get comments to server
                      sendData();
                      //if (passwordCorrection(inputUsername, inputPassWord)) {
                      //setState(
                      //() {
                      //logedIn = true;
                      //passWord = _textControllerPassword.text;
                      //username = _textControllerUsername.text;
                      //},
                      //);
                      //} else {
                      //AwesomeDialog(
                      //      context: context,
                      //    dialogType: DialogType.error,
                      //  animType: AnimType.rightSlide,
                      //title: 'Kullanıcı Adı ya da Şifre Yanlış',
                      //titleTextStyle: const TextStyle(fontSize: 15),
                      //desc: '',
                      //btnOkText: 'Tamam',
                      //btnOkOnPress: () {})
                      //.show();
                      //}
                    },
                    child: const Text('Giriş Yap'),
                  ),
                ]),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

//anasayfa

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: const Text('Ana Sayfa'),
            backgroundColor: const Color.fromARGB(255, 77, 222, 255),
          ),
          body: Center(
            child: SizedBox(
              width: double.infinity,
              height: double.infinity,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(''),
                  Row(
                    children: [
                      const Text('   '),
                      SizedBox(
                        width: 166,
                        height: 166,
                        child: ElevatedButton(
                          onPressed: () {
                            //yemek bölümünü aç

                            appBarTopicYemek = 'Restorantlar';
                            _indexCurrent = 0;
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => const Yemek(),
                              ),
                            );
                          },
                          child: const Text('Yemek'),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class Yemek extends StatefulWidget {
  const Yemek({super.key});

  @override
  State<Yemek> createState() => _YemekState();
}

//yemek bölümü

class _YemekState extends State<Yemek> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          appBar: AppBar(
            leading: BackButton(
              onPressed: () {
                //anasayfaya yönlendir

                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const MainPage(),
                  ),
                );
              },
            ),
            centerTitle: true,
            title: Text(appBarTopicYemek),
            backgroundColor: const Color.fromARGB(255, 77, 222, 255),
          ),
          body: Center(
            child: _indexCurrent == 0
                ? SizedBox(
                    //homepage

                    width: double.infinity,
                    height: double.infinity,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        const Text(
                          'DENÜŞ \n',
                          style: TextStyle(fontSize: 25),
                        ),
                        Text('$_x \n'),
                        SizedBox(
                          width: 125,
                          height: 66,
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor:
                                  const Color.fromARGB(255, 0, 216, 231),
                              foregroundColor:
                                  const Color.fromARGB(255, 0, 0, 0),
                            ),
                            onPressed: () {
                              setState(
                                () {
                                  _x++;
                                },
                              );
                            },
                            child: const Text('Click'),
                          ),
                        ),
                      ],
                    ),
                  )
                : _indexCurrent == 1
                    ? SizedBox(
                        //Wallet

                        height: double.infinity,
                        width: double.infinity,
                        child: Column(
                          children: [
                            const Text(' \n \n'),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                SizedBox(
                                  height: 45,
                                  width: 45,
                                  child: ElevatedButton(
                                    onPressed: () {
                                      setState(
                                        () {
                                          _bakiye += 1;
                                        },
                                      );
                                    },
                                    child: const Text(
                                      '+ ',
                                      style: TextStyle(fontSize: 35),
                                    ),
                                  ),
                                ),
                                Text(
                                  '  $_bakiye TL  ',
                                  style: const TextStyle(fontSize: 60),
                                ),
                                SizedBox(
                                  width: 45,
                                  height: 45,
                                  child: ElevatedButton(
                                    onPressed: () {
                                      setState(
                                        () {
                                          if (_bakiye >= 1) {
                                            _bakiye += -1;
                                          }
                                        },
                                      );
                                    },
                                    child: const Text(
                                      '-',
                                      style: TextStyle(fontSize: 35),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      )
                    : logedIn == false
                        ? SizedBox(
                            //User

                            width: double.infinity,
                            height: double.infinity,
                            child: Column(
                              children: [
                                ElevatedButton(
                                  onPressed: () {
                                    AwesomeDialog(
                                      context: context,
                                      dialogType: DialogType.noHeader,
                                      animType: AnimType.rightSlide,
                                      title: 'Kaydol Ya Da Giriş Yap',
                                      titleTextStyle:
                                          const TextStyle(fontSize: 40),
                                      desc: '',
                                      btnCancel: ElevatedButton(
                                          onPressed: () {},
                                          child: const Text('Kaydol')),
                                      btnOk: ElevatedButton(
                                          onPressed: () {
                                            Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                    builder: (context) =>
                                                        const LogInPage()));
                                          },
                                          child: const Text('Giriş Yap')),
                                    ).show();
                                  },
                                  child: const Text('Giriş Yap'),
                                ),
                              ],
                            ),
                          )
                        : const SizedBox(
                            child: Text('Work in progress'),
                          ),
          ),
          bottomNavigationBar: BottomNavigationBar(
            items: const [
              BottomNavigationBarItem(
                label: 'home',
                icon: Icon(Icons.home),
              ),
              BottomNavigationBarItem(
                label: 'wallet',
                icon: Icon(Icons.wallet),
              ),
              BottomNavigationBarItem(
                label: 'User Settings',
                icon: Icon(Icons.supervised_user_circle_rounded),
              )
            ],
            currentIndex: _indexCurrent,
            onTap: (int index) {
              setState(
                () {
                  _indexCurrent = index;
                  if (index == 0) {
                    appBarTopicYemek = 'Restoranlar';
                  }

                  if (index == 1) {
                    appBarTopicYemek = 'Cüzdan';
                  }

                  if (index == 2) {
                    appBarTopicYemek = 'Kullanıcı Ayarları';
                  }
                },
              );
            },
          ),
        ),
      ),
    );
  }
}

void sendData() async {
  final channel = WebSocketChannel.connect(Uri.parse('ws://$HOST:$PORT'));
  channel.sink.add(
  json.encode('FU'));
  channel.stream.listen((data) {
  String msg = data;
  print(msg);
  },
 );
}

String setVariable(
    String username, String password, String nameOfVar, String newValue) {
  final channel = WebSocketChannel.connect(Uri.parse('wss://$HOST:$PORT'));
  //send comment to server
  String msg = 'null';
  channel.sink.add(
      json.encode('SET\$$nameOfVar\$$newValue\$$username\$$passWord'));
  //get msg from server (msg shows if username or password correct)
  channel.stream.listen(
    (data) {
      msg =json.decode(data);
    },
  );
  channel.sink.close(status.goingAway);
  return msg;
}

int getVariable(String username, String password, String nameOfVar) {
  final channel = WebSocketChannel.connect(Uri.parse('wss://$HOST:$PORT'));
  int msg = 0;
  channel.sink
      .add(json.encode('SET\$$nameOfVar\$$username\$$passWord'));
  channel.stream.listen(
    (data) {
      msg = int.parse(json.decode(data));
    },
  );
  channel.sink.close(status.goingAway);
  return msg;
}

bool passwordCorrection(username, password) {
  final channel = WebSocketChannel.connect(Uri.parse('wss://$HOST:$PORT'));
  bool correct = false;
  channel.sink
      .add(json.encode('PASSWORDCORRECTION\$$username\$$passWord'));
  channel.stream.listen(
    (data) {
      if (data == 1) {
        correct = true;
      }
    },
  );

}

Python server kodu:

import socket
from json import dump,loads,load
from time import sleep as s


class Database():
    def __init__(self, HOST, PORT, FİLE):
        self.HOST = HOST
        self.PORT = PORT
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.file = open(FİLE,"r+",encoding="utf-8")
        self.collection = load(self.file)

    def connect(self):
        try:
            self.socket.bind((self.HOST, self.PORT))
            self.socket.listen()
        except:
            print('Denüjüm bağlayamadı((((((((()))))))))')
    
    def get_operation(self):
            
            c, addr = self.socket.accept()
            print(f"{addr} connected.")
            try:
                msg = c.recv(1024).decode('utf-8').split("$")
            

                if msg[0] == "SET":
                #1 = variable that we want to change
                #2 = new value of the variable
                #3 = username
                #4 = password
                    if self.collection[msg[3]]["password"]["value"] == msg[4]:
                    #make that dont delete everythink and add a new variable. change the variables value, if it is not possible create new variable with that name
                        if msg[1] in self.collection[msg[3]]:
                            if self.collection[msg[3]][msg[1]]["changeable"]:
                                self.collection[msg[3]][msg[1]]["value"] = msg[2]
                                c.send(repr(1).encode())
                                print(f"{addr} changed {msg[1]}'s value to {msg[2]}")
                            else:
                                print(f"{addr} want to change {msg[1]} but {msg[1]} isnt changeable")
                                c.send(repr(3).encode())
                        else:
                            print(f"{addr}'s want to change {msg[1]} but it doesn't exist")
                            c.send(repr(2).encode())
                    else:
                        c.send(repr(0).encode())
                        print(f"{addr}'s want to change {msg[1]} but password is wrong")
                    
                elif msg[0] == "GET":
                    if self.collection[msg[2]]["password"]["value"] == msg[3]:
                        if msg[1] in self.collection[msg[2]]:
                            print(f"{addr}'s got {msg[1]}'s value")
                            c.send(repr(self.collection[msg[2]][msg[1]]["value"]).encode())
                        else:
                            print(f"{addr}'s want to get {msg[1]} but it doesn't exist")
                    else:
                        print(f"{addr}'s want to get {msg[1]} but password is wrong ")

                elif msg[0] == "SIGNUP":
                #send correction mail to msg[3]
                    self.collection[msg[1]]["password"]["value"] = msg[2]
                    c.send(repr(1).encode())

                elif msg[0] == "PASSWORDCORRECTION":
                    if self.collection[msg[1]]["password"]["value"] == msg[2]:
                        c.send(repr(1).encode())
                    else:
                        c.send(repr(0).encode())


                elif msg[0] == "FU":
                    print("FUUUUUU\n\n\n\n\n\n\nFUUUUUU")

                else:
                    print(f"Got a unknown foncion: {msg}")
                    c.send(repr(0).encode())
            except Exception as e:
                print(c.recv(1024))
                print(f"Unable to use: {e}")

                    
HOST = "localhost"
PORT = 4609
FİLE = "infs.json"

db = Database(HOST, PORT, FİLE)
db.connect()

while True:
    db.get_operation()

Merhaba. Kodu pek incelemedim ancak websocket ile socket farklı protokoller. Haberleşme için iki tarafta da aynı protokolü kullanmanız lazım.

1 Beğeni