微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何通过套接字将 Dart / Flutter 与 C 语言连接起来?

如何解决如何通过套接字将 Dart / Flutter 与 C 语言连接起来?

我正在尝试在 Linux 和 C 语言上使用 Flutter 为桌面制作一个非常简单的应用程序。在前端(Flutter)上,我想通过计算机中的套接字向服务器(C 语言)发送和接收消息。当我运行时,两者都建立了连接,但没有发送或接收消息。

这个想法是让服务器在终端上持续运行等待消息,根据哪一个,它要么在终端上打印前端发送的消息,要么向前端发送消息或关闭服务器。我对套接字的概念很陌生,感谢您的帮助:)

这是前端(客户端)颤振代码

import 'package:Flutter/material.dart';
import 'dart:io';
import 'dart:typed_data';

void main() async {
  final socket = await Socket.connect('localhost',4242);
  print('Connected to: ${socket.remoteAddress.address}:${socket.remotePort}');

  runApp(MaterialApp(
    home: HomeTest(socket: socket),debugShowCheckedModeBanner: false,title: "Test Socket",));

  socket.destroy();
}

class HomeTest extends StatefulWidget {
  final Socket socket;
  const HomeTest({Key key,this.socket}) : super(key: key);

  @override
  _HomeTestState createState() => _HomeTestState();
}

class _HomeTestState extends State<HomeTest> {

  TextEditingController sendController = TextEditingController();
  TextEditingController receiveController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        children: <Widget>[
          Expanded(
            child: Padding(
              padding: EdgeInsets.fromLTRB(20.0,0.0,20.0,0.0),child: Column(
                mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
                  TextField(
                    style: TextStyle(fontSize: 20.0),controller: sendController,),Divider(color: Colors.white),ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      primary: Colors.deepPurple
                    ),child: Text("Send message",style: TextStyle(color: Colors.white)),onpressed: (){
                      /* tells the server that the client is going to send a message */
                      widget.socket.write("send");
                      /* sends a message to the server */
                      widget.socket.write(sendController.text);
                      sendController.text = "";
                    }
                  )
                ]
              )
            )
          ),Expanded(
            child: Padding(
              padding: EdgeInsets.fromLTRB(20.0,controller: receiveController,readOnly: true,child: Text("Receive message",onpressed: (){
                      /* tells the server that the client wants to receive a message */
                      widget.socket.write("receive");
                      setState(() {
                        /* receives a message from the server and shows it in the text field above */
                        widget.socket.listen(
                          (Uint8List data) {
                            final serverResponse = String.fromCharCodes(data);
                            receiveController.text = serverResponse;
                          }
                        ); 
                      });
                    }
                  )
                ]
              )
            )
          ),child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  primary: Colors.deepPurple
                ),child: Text("End connection",onpressed: (){
                  /* sends message to shut down the server */
                  widget.socket.write("close");
                }
              )
            )
          )
        ]
      )
    );
  }
}

这是服务器的 C 代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define PORT 4242
#define BUFFER_LENGTH 4096

int main(void){

    /* Client and Server socket structures */
    struct sockaddr_in client,server;

    /* File descriptors of client and server */
    int serverfd,clientfd;

    char buffer[BUFFER_LENGTH];

    fprintf(stdout,"Starting server\n");

    /* Creates a IPv4 socket */
    serverfd = socket(AF_INET,SOCK_STREAM,0);
    if(serverfd == -1) {
        perror("Can't create the server socket:");
        return EXIT_FAILURE;
    }
    fprintf(stdout,"Server socket created with fd: %d\n",serverfd);

    /* Defines the server socket properties */
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    memset(server.sin_zero,0x0,8);

    /* Handle the error of the port already in use */
    int yes = 1;
    if(setsockopt(serverfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
        perror("Socket options error:");
        return EXIT_FAILURE;
    }

    /* bind the socket to a port */
    if(bind(serverfd,(struct sockaddr*)&server,sizeof(server)) == -1 ) {
        perror("Socket bind error:");
        return EXIT_FAILURE;
    }

    /* Starts to wait connections from clients */
    if(listen(serverfd,1) == -1) {
        perror("Listen error:");
        return EXIT_FAILURE;
    }
    fprintf(stdout,"Listening on port %d\n",PORT);

    socklen_t client_len = sizeof(client);
    if ((clientfd=accept(serverfd,(struct sockaddr *) &client,&client_len )) == -1) {
        perror("Accept error:");
        return EXIT_FAILURE;
    }
    fprintf(stdout,"Client connected.\nWaiting for client message ...\n");

    do {
        /* Zeroing buffers */
        memset(buffer,BUFFER_LENGTH);
        
        int message_len;
        /* buffer value: 'send' or 'receive' or 'close' */
        if((message_len = recv(clientfd,buffer,BUFFER_LENGTH,0)) > 0) {
            buffer[message_len - 1] = '\0';

            /* client will send a message to the server */
            if(strcmp(buffer,"send")){
                memset(buffer,BUFFER_LENGTH);
                /* receive the message and print */
                if((message_len = recv(clientfd,0)) > 0) {
                    buffer[message_len - 1] = '\0';
                    printf("Message: %s",buffer);
                }
            }
            /* client wants to receive a message from the server */
            else if(strcmp(buffer,"receive")){
                send(clientfd,"any message",13,0);
            }

        }
    /* client sent a message to shut down the server */
    } while(strcmp(buffer,"close"));
        
    close(clientfd);
    close(serverfd);
    printf("Connection closed\n\n");

    return EXIT_SUCCESS;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。