Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a tcp client with electron

Tags:

electron

Is it possible to create a tcp client with electron? Or can we access the chrome socket api with does that?

https://developer.chrome.com/apps/sockets_tcp

like image 355
tbo47 Avatar asked Jan 16 '17 10:01

tbo47


1 Answers

You can use the Node net API in Electron to implement a TCP client.

Try this sample code (don't forget to change IP address) with a little socket server as SocketTest java application for example (HERE).

At the connection, you should see a "World!" string on server side. Try to send this message from server:

{
    "nom":"Xplorer",
    "prenom":"Yann"
}

And you should see Hello Yann! in your electron console.

'use strict';

const electron = require('electron');

const path = require('path');
const url = require('url');
const net = require('net');

const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

let mainWindow;
var socketClient

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600,backgroundColor:'#FFFFFF', frame:false})

  // and load the index.html of the app.
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname+'/html/', 'main.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  //mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })

  /* Instance socket on create window */
  console.log('Try to connect');
  socketClient = net.connect({host:'192.16.122.3', port:9042},  () => {
    // 'connect' listener
    console.log('connected to server!');
    socketClient.write('world!\r\n');
  });

  socketClient.on('data', (data) => {
    console.log(data.toString());
    var person = JSON.parse(data);

    console.log('Hello '+person.prenom+"!");

  });
  socketClient.on('end', () => {
    console.log('disconnected from server');
  });

  //mainWindow.openDevTools();
}
app.on('before-quit',function(){
  socketClient.end();
})

see you.

like image 67
YannXplorer Avatar answered Sep 21 '22 13:09

YannXplorer