是否可以使用电子创建 tcp 客户端?或者我们可以访问chrome socket api吗?
小智 6
您可以使用节点netAPIElectron 中来实现 TCP 客户端。
试试这个示例代码(不要忘记更改 IP 地址),使用一个小套接字服务器作为 SocketTest java 应用程序(这里)。
在连接处,您应该看到“世界!” 服务器端的字符串。尝试从服务器发送此消息:
{
"nom":"Xplorer",
"prenom":"Yann"
}
Run Code Online (Sandbox Code Playgroud)
你应该看到你好 Yann!在您的电子控制台中。
'use strict';
const electron = require('electron');
const app = electron.app;
const path = require('path');
const url = require('url');
const net = require('net');
const BrowserWindow = electron.BrowserWindow;
let mainWindow;
var socketClient
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();
})
Run Code Online (Sandbox Code Playgroud)
再见。
| 归档时间: |
|
| 查看次数: |
13332 次 |
| 最近记录: |