Samuel Kodytek
Samuel Kodytek

Reputation: 1024

Java Socket and JS WebSocket

So I am trying to make some sort of connection between my Java app and my Web app, I looked up websockets and they look really simple and easy to use :). And I created myself a Java Server, which uses the ServerSocket class.

Now the problem is I am able to connect to the server from the web, with the websocket, but I am unable to send data to the server... but when I tried to send data from a Java Client it worked fine... what might be the problem?

My Java/Scala (I followed this tutorial: https://www.tutorialspoint.com/java/java_networking.htm) server:

class Server(val port: Int) extends Thread {

  private val serverSocket = new ServerSocket(port)

  override def run(): Unit = {
    try {
      while(true) {
        println("Waiting for client on port: " + serverSocket.getLocalPort)
        val server = serverSocket.accept()

        println(server.getRemoteSocketAddress)
        val in = new DataInputStream(server.getInputStream())
        println(in.readUTF())
        val out = new DataOutputStream(server.getOutputStream())
        out.writeUTF("Hello world!")
        server.close()
      }
    } catch {
      case s: SocketTimeoutException => println("Connection timed out!");
      case e: Exception => e.printStackTrace()
    }
  }
}

My web js (I followed https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications ):

/**
 * Created by samuelkodytek on 20/12/2016.
 */
var conn = new WebSocket('ws://127.0.0.1:8080');

conn.onopen = function(e) {
    console.log("Connection established!");
    conn.send("Hello!");
};

conn.onmessage = function(e) {
    console.log(e.data);
};

Upvotes: 0

Views: 2167

Answers (1)

Jon Trauntvein
Jon Trauntvein

Reputation: 4554

A web socket server is not the same thing as a simple socket server. A server that offers web sockets must first offer HTTP or HTTPS services because the web socket is established when a web client sends an HTTP request with an Upgrade option and special fields for establishing the web socket. Even after the web socket is established, the connection still does not behave exactly like a regular socket. The Web Socket protocol uses frames to send or receive data. This is all considerably different from what you seem to expect.

One other thing that you should be aware of is that the browser will enforce the rule that the web socket must come from the same host as the page that is attempting to establish the web socket (the same protocol, address, and TCP port).

Upvotes: 3

Related Questions