Javascript ping ip пример

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

JavaScript client side ping API.

License

jdfreder/pingjs

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Читайте также:  Timezone get offset java

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

JavaScript ping API for use in a web browser context. Released under the BSD-3-Clause license, see LICENSE.

There are three possible ways to install this.

Drag and drop the ping.js file next to an HTML file. Inside the tag of the HTML file, use a script tag to load ping.js.

script src pl-s">./ping.js">script>

npm install —save web-pingjs

bower install —save web-pingjs

This library uses a UMD header that allows it to be loaded as CommonJS, AMD, or a window global object.

A single function is exported, ping . Ping’s signature follows:

/** * Pings a url. * @param String> url * @param Number> multiplier - optional, factor to adjust the ping by. 0.3 works well for HTTP servers. * @return Promise> promise that resolves to a ping (ms, float). */
ping('https://google.com/').then(function(delta)  console.log('Ping time was ' + String(delta) + ' ms'); >).catch(function(err)  console.error('Could not ping remote URL', err); >);

The user should be aware that this method relies on the HTTP protocol to ping remote URLs. Consequently, ping times are not as reliable as if they were performed using the ICMP protocol.

About

JavaScript client side ping API.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

🔔 Ping the web with Javascript.

alfg/ping.js

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Ping.js is a small and simple Javascript library for the browser to «ping» response times to web servers in Javascript! This is useful for when you want to display realtime ping times on a status page which are relative to the user.

See Notes below for how this works.

This module is for the browser only as it depends on the brower’s Image API.

var p = new Ping(); // Using callback p.ping("https://github.com", function(err, data)  // Also display error if err is returned. if (err)  console.log("error loading resource") data = data + " " + err; > document.getElementById("ping-github").innerHTML = data; >); // You may use Promise if the browser supports ES6 p.ping("https://github.com") .then(data =>  console.log("Successful ping: " + data); >) .catch(data =>  console.error("Ping failed: " + data); >)
script src pl-s">https://cdn.jsdelivr.net/gh/alfg/ping.js@0.2.2/dist/ping.min.js" type pl-s">text/javascript">script>

See demo/react-example for an example in React.

  • Type: Object
  • favicon : Override the default favicon.ico image location.
  • timeout : Optional — Set a timeout in milliseconds.

Creates a ping request to the source . Returns a promise that resolves and rejects to the response time in milliseconds, or if the browser does not supports Promise, returns undefined.

  • source : IP address or website URL, including protocol and port (optional). Example: https://example.com:8080
  • callback(err, ping) : Optional — Callback function which returns an error and the response time in milliseconds.
git clone https://github.com/alfg/ping.js.git cd ping.js npm install npm install -g grunt-cli 

Run grunt to build distribution files:

Open demo/index.html in a browser to test results.

Javascript itself doesn’t have a native way of sending a «ping», so results may not be completely accurate. Since xhr requests are affected by cross-domain issues (CORS), they are blocked by default. ping.js is using a method of loading a favicon.ico image from any host and timing the response time. If the favicon image doesn’t exist, an error is returned along with the ping value. If there’s a better way to do this in Javascript, feel free to create an issue, or pull request so I can review.

Источник

Можно ли пинговать сервер из Javascript?

Я создаю веб-приложение, которое требует, чтобы я проверял, находятся ли удаленные серверы в сети или нет. Когда я запускаю его из командной строки, моя загрузка страницы достигает 60 секунд (для 8 записей она будет масштабироваться линейно с большим количеством). Я решил пойти по маршруту pinging в конце пользователя. Таким образом, я могу загрузить страницу и просто ждать, пока данные «сервер будут в сети» во время просмотра моего контента. Если у кого-то есть ответ на вышеупомянутый вопрос, или если они знают, как быстро поддерживать загрузку моей страницы, я бы определенно ее оценил.

16 ответов

Я нашел кого-то, кто выполняет это с очень умным использованием собственного Image объекта. Из их источника это основная функция (она имеет зависимости от других частей источника, но вы получаете идею).

function Pinger_ping(ip, callback) < if(!this.inUse) < this.inUse = true; this.callback = callback this.ip = ip; var _that = this; this.img = new Image(); this.img.onload = function() ; this.img.onerror = function() ; this.start = new Date().getTime(); this.img.src = "http://" + ip; this.timer = setTimeout(function() < _that.bad();>, 1500); > > 

Это работает на всех тестируемых серверах (веб-серверах, ftp-серверах и игровых серверах). Он также работает с портами. Если кто-либо сталкивается с прецедентом, который терпит неудачу, напишите в комментариях, и я обновлю свой ответ. Обновить. Предыдущая ссылка удалена. Если кто-либо находит или реализует вышеизложенное, прокомментируйте, и я добавлю его в ответ. Обновление 2: @trante было достаточно приятно, чтобы предоставить jsFiddle. http://jsfiddle.net/GSSCD/203/ Обновление 3: @Jonathon создал репозиторий GitHub с реализацией. https://github.com/jdfreder/pingjs Обновление 4. Похоже, что эта реализация перестала быть надежной. Люди также сообщают, что Chrome больше не поддерживает все это, бросая ошибку net::ERR_NAME_NOT_RESOLVED . Если кто-то может проверить альтернативное решение, я поставлю это как принятый ответ.

Это то, что я использовал. Однако у него есть один недостаток, и это то, что «изображение» кэшируется. Когда я пингую данный IP изначально, я получаю 304 мс — но если я пингую его второй раз без перезагрузки страницы, я получаю 2 мс. Этого можно избежать, добавив «/?cachebreaker=»+new Date().getTime(); до конца img src, если необходимо.

Хороший улов. Я действительно заметил это, но предположил, что это неизбежно. Добавление любого слизняка к концу должно определенно исправить это все же.

Источник

Node.js: How to Ping a Remote Server/ Website

This article shows you a couple of different ways to programmatically ping a remote server or a website from within your Node.js application (to get some network information like latency, IP address, …). In the first approach, we will solve the task ourselves by writing code from scratch. In the second one, we will get the job done quickly by using a third-party package.

Using self-written code

The strategy here is to perform the ping command provided by the operating system (Linux, macOS, Windows) in our Node.js app. Fortunately, we can do that easily with the help of the child_process module of Node.js.

// kindacode.com // this example uses ES modules (import) instead of CommonJS (require) import util from 'util' import < createRequire >from "module"; const require = createRequire(import.meta.url); const exec = util.promisify(require('child_process').exec); const ping = async (host) => < const = await exec(`ping -c 5 $`); console.log(stdout); console.log(stderr); > ping('www.kindacode.com'); 
PING www.kindacode.com (104.21.33.69): 56 data bytes 64 bytes from 104.21.33.69: icmp_seq=0 ttl=59 time=38.733 ms 64 bytes from 104.21.33.69: icmp_seq=1 ttl=59 time=37.775 ms 64 bytes from 104.21.33.69: icmp_seq=2 ttl=59 time=137.648 ms 64 bytes from 104.21.33.69: icmp_seq=3 ttl=59 time=42.290 ms 64 bytes from 104.21.33.69: icmp_seq=4 ttl=59 time=34.817 ms --- www.kindacode.com ping statistics --- 5 packets transmitted, 5 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 34.817/58.253/137.648/39.769 ms

The output you get might be different from mine (depending on your location and network).

Using a 3rd library

Even though ping stuff is not a big challenge in Node.js, many developers prefer to use a pre-made library. A great one for this case is ping (you can freely use it under the MIT License).

// kindacode.com // this example uses ES Modules (import) instead of CommonJS (require) import ping from 'ping' (async function () < const result = await ping.promise.probe('www.kindacode.com', < timeout: 10, extra: ["-i", "2"], >); console.log(result); >)();

Conclusion

We’ve walked through more than one technique to ping a remote host with some lines of code. If you’d like to explore more new and exciting things in the modern Node.js world, take a look at the following articles:

You can also check out our Node.js category page or PHP category page for the latest tutorials and examples.

Источник

Оцените статью