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:

import java.net.*;
import java.io.*;

public class ServerCommunicator extends Thread{

    private final static int PORT = 7777;

    private static ServerSocket serverSocket;
    private static Server server;

    private Socket incoming;
    private DataOutputStream out;
    private DataInputStream in;

    public static void main (String args[]) 
    {
        try {
            serverSocket = new ServerSocket (PORT);
            System.out.println("Waiting for Clients..");

            server = new Server();

            while (true) {
                Socket incoming = serverSocket.accept();
                ServerCommunicator communicator = new ServerCommunicator(incoming);
                communicator.start();
            }
        }catch (Exception e) {e.printStackTrace();}
    }

    public ServerCommunicator (Socket incoming)
    {
        this.incoming = incoming;

        try {
            out = new DataOutputStream (incoming.getOutputStream());
            in = new DataInputStream (incoming.getInputStream());
        } catch (Exception e) {e.printStackTrace();}
    }

        public void run()
        {

            try {
                String input = in.readLine();
                String reply;
                reply = server.auszaehlen(input);   //returns a String
                out.writeUTF(reply);

                out.flush();
                incoming.close();
            } catch (Exception e) {e.printStackTrace();}
        }
}

Javascript code HTML:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     alert("WebSocket is supported by your Browser!");
     // Let us open a web socket
     var ws = new WebSocket("ws://localhost:7777");
     ws.onopen = function()
     {
        // Web Socket is connected, send data using send()
        ws.send("zustimmung");
        alert("Message is sent...");
     };
     ws.onmessage = function (evt)
     {
        var received_msg = evt.data;
        alert("Message is received...");
     };
     ws.onclose = function()
     {
        // websocket is closed.
        alert("Connection is closed...");
     };
  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
}
</script>
</head>
<body>
<div id="sse">
   <a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>

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:

GET / HTTP/1.1
Host: example.com
Accept: *

zustimmung

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:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement