Electron 中使用 TCP 和 WebSocket 通信


在上一篇文章《Electron與工業CCD通過TCP Server協議連接通訊》中,當時為了實現需求,草率的實驗成功了,但是發現里面還有很多瑕疵,經過今天一上午的學習研究,我想再優化一下,補充的更加完善一點。在昨天的文章里,我們是在Electron的主進程中實現TCP連接的,這樣是很不方便的,這次我們把TCP連接直接放到渲染進程中實現,並對其簡單封裝一下。

具體 API 參考資料:http://nodejs.cn/api/net.html#net_event_close_1

1、Electron 中使用 TCP 通信

把上篇文章中主進程中關於TCP連接的代碼注釋掉,或者直接去掉,我們在渲染進程中實現TCP連接。渲染進程是無法直接使用主進程中net模塊的,所以第一步我們將net模塊引入到渲染進程的頁面中。

// 引入 net 模塊
const net = window.require("net");

在Home.vue中:

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <div>發送的消息:<input type="text" v-model="msg" /></div>
    <div>接收的消息:<input type="text" v-model="msg2" /></div>
    <div>
      <button @click="tcpClick">發送</button>
    </div>
    <!-- <HelloWorld msg="Welcome to Your Vue.js App" /> -->
  </div>
</template>

<script>
// 引入 net 模塊
const net = window.require("net");
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";

export default {
  name: "Home",
  components: {
    HelloWorld,
  },
  data() {
    return {
      client: null,
      HOST: "127.0.0.1",
      PORT: 7899,
      msg: "",
      msg2: "",
    };
  },
  created() {},
  mounted() {
    // console.log(net);
    this.initTcp();
    this.connect(this.PORT, this.HOST);
    this.data();
    this.close()
    // this.tcpClicent(this.PORT,this.HOST,'hellow TCP')
  },
  destroyed() {},
  methods: {
    // 初始化TCP連接
    initTcp() {
      this.client = new net.Socket();
    },
    // 當一個 socket 連接成功建立的時候觸發該事件。
    connect(PORT, HOST) {
      this.client.connect(PORT, HOST, () => {
        console.log("連接成功: " + HOST + ":" + PORT);
        // 建立連接后立即向服務器發送數據,服務器將收到這些數據
        this.sendMsgToTcp('hellow TCP,Fuck you!')
      });
    },
    // 當接收到數據的時觸發該事件。
    data() {
      this.client.on("data", (data) => {
        console.log("DATA: " + data);
        this.msg2 = data;
        this.destroyTcp();
      });
    },
    // 一旦 socket 完全關閉就發出該事件, 監聽連接關閉事件
    close() {
      this.client.on("close", function () {
        console.log("關閉連接");
      });
    },
    // 向服務器發送數據,服務器將收到這些數據
    sendMsgToTcp(msg) {
      this.client.write(msg);
    },
    // 手動關閉連接
    destroyTcp() {
      this.client.destroy();
    },
    tcpClick() {
      console.log(this.msg);
      this.sendMsgToTcp(this.msg);
    },
  },
};
</script>

<style lang="css" scoped>
img {
  -webkit-app-region: drag;
}
</style>

頁面展示:

使用網絡調試助手,開啟一個 127.0.0.1:7899 的 TCP Server

啟動Electron項目,Home頁面一加載,就會向TCP服務器發送一條數據,如下圖所示:

測試發送消息,在發送的消息輸入框中輸入消息,點擊發送按鈕,結果如下圖:

測試接收消息,在網絡調試助手中,輸入消息后點擊發送按鈕,結果如下圖所示:

接收到消息后,我就手動關閉連接了,所以打印出了關閉連接

// 當接收到數據的時觸發該事件。
data() {
   this.client.on("data", (data) => {
     console.log("DATA: " + data);
       this.msg2 = data;
       this.destroyTcp();
   });
},
// 手動關閉連接
destroyTcp() {
   this.client.destroy();
},
// 一旦 socket 完全關閉就發出該事件, 監聽連接關閉事件
close() {
   this.client.on("close", function () {
      console.log("關閉連接");
   });
},

2、Electron 中使用 WebSocket 通信

Electron 中使用 WebSocket 通信是非常簡單的,直接寫代碼即可:

<template>
  <div>
    <h1>websocket</h1>
    <el-input v-model="sendMessage" placeholder="請輸入內容"></el-input>
    <el-button size="mini" type="primary" @click="send">發送消息</el-button>
    <el-input
      type="textarea"
      :autosize="{ minRows: 2, maxRows: 4}"
      placeholder="收到的消息"
      v-model="textarea2"
    ></el-input>
    <div>{{testMsg | addZero}}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      path: "ws://192.168.43.50:8082/websocket1",
      socket: "",
      sendMessage: "",
      textarea2: "",
      testMsg: 9,
    };
  },
  mounted() {
    // 初始化
    this.init();
    if (this.socket.readyState != this.socket.OPEN) {
      console.log("連接已中斷!");
      //todo...
      this.init();
      return false;
    }
  },
  destroyed() {
    // 銷毀監聽
    this.socket.onclose = this.close;
  },
  methods: {
    init() {
      if (typeof WebSocket === "undefined") {
        alert("您的瀏覽器不支持socket");
      } else {
        // 實例化socket
        this.socket = new WebSocket(this.path);
        // 監聽socket連接
        this.socket.onopen = this.open;
        // 監聽socket錯誤信息
        this.socket.onerror = this.error;
        // 監聽socket消息
        this.socket.onmessage = this.getMessage;
        this.socket.onclose = this.close;
      }
    },
    open() {
      console.log("socket連接成功");
    },
    error() {
      console.log("連接錯誤");
      this.init();
    },
    getMessage(msg) {
      // 得到服務器返回的數據
      console.log(msg);
      this.textarea2 = msg.data;
    },
    send() {
      console.log("發送消息");
      this.socket.send(this.sendMessage);
    },
    close() {
      console.log("socket已經關閉");
    },
  },
};
</script>

<style lang="scss" scoped>
</style>

所有文章都會首發於我的微信公眾號:小笑殘虹,歡迎大家關注,一起交流進步

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM