Skip to content
Advertisement

Java Server Socket transfer String to web socket

My goal is to set up a connection between a Java Server Socket and a browser (using web sockets). So far, the connection works, but my data streams do not. I would like to send a String from the server socket to the web socket.

The problems are the input and output streams. The web socket sends “zustimmung” to the server socket which is read in the run() by in.readLine(). But this does not read the String, it reads “GET / HTTP/1.1”.

The Output also does not work (I’m guessing it’s due to the writeUTF()).

So my question: What data streams can I use to transfer the Strings between the web socket and the server socket?

Code Server:

JavaScript

Javascript code HTML:

JavaScript

Advertisement

Answer

When you connect using a web socket, it sends an HTTP request, which is more than just a socket connection. A HTTP request opens the socket, sends some meta information, and then sends the data.

What you are reading on the server is the first line of that meta information. A typical HTTP request to your server should be multiple lines and should look like:

JavaScript

There may be multiple header lines that you need to read, then a blank line, and then your data. Your server is only reading one line. You will need a loop to read several lines, look for the blank line, and then read your data.

Wikipedia has good examples of what the request and response should look like. Here is their example response:

JavaScript
Advertisement