-2

The code below sends "ping" to my localhost server in java, how would I do the same thing in JavaScript?

new PrintWriter(new Socket("127.0.0.1", 9002).getOutputStream(), true).println("ping");

I ran it in javaScript and it said:

Uncaught ReferenceError: PrintWriter is not defined

Mark
  • 13
  • 6
  • just to clarify, what exactly is the code you ran in Javascript? how you ran it (in browser console?)? – Jos Jul 29 '15 at 18:13
  • A Chrome Extension Where you can put javascript on any page. I ran the exact same code I pasted above for java in JavaScript https://chrome.google.com/webstore/detail/custom-javascript-for-web/poakhlngfciodnhlhhgnaaelnpjljija – Mark Jul 29 '15 at 18:14
  • 1
    hope you understand that Java and Javascript are entirely different languages and the only thing common is the similarity in name... forgive me if you already know.. – Jos Jul 29 '15 at 18:15
  • I know, but some thinks like if statements work in both :P I taught i'd try it, So what i'm asking here is: How would I send a message to a server using JavaScript? – Mark Jul 29 '15 at 18:18
  • PrintWriter is a java specific class, you dont have a function or class in javascript with same name. Also I think it wouldn't be easy to achieve this functionality using javascript. – Jos Jul 29 '15 at 18:19
  • To send message/data to server from javascript you have to use ajax requests. http://www.w3schools.com/Ajax/ajax_intro.asp – Jos Jul 29 '15 at 18:21
  • that error tells me you have tried literally nothing but copy and paste the same code into a javascript engine. Figure out what it does, attempt to replicate it in javascript, and if you still cant figure it out, **THEN** come ask a question. – Epicblood Jul 29 '15 at 18:22
  • http://html5doctor.com/methods-of-communication/ – Jos Jul 29 '15 at 18:22

1 Answers1

2

Java and JavaScript are two entirely-different languages. The similarity in names is due to an unfortunate PR decision in the 90's on Netscape's part. You can't expect Java code to "just work" in JavaScript for a multitude of reasons; it's like expecting COBOL code to be compiled and understood by a C compiler.

The standard way to send a "ping" to a server is to use XMLHttpRequest. Keep in mind though, that there is a same-origin-policy restriction. What this means is that you can only make requests to resources on the same subdomain.

There are a few ways around this; take a look at the following answer for details:

Community
  • 1
  • 1
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295