0

Java Code I make cross platform and need open socket with javascript to send from smart watch to computer i need help from send data I opened the connection but can send any data

   public class ChatSocketServer {
    private ServerSocket severSocket = null;
    private Socket socket = null;
    private InputStream inStream = null;
    private OutputStream outStream = null;

    public ChatSocketServer() {

    }

    public void createSocket() {
        try {
            ServerSocket serverSocket = new ServerSocket(3339);
            while (true) {
                socket = serverSocket.accept();
                inStream = socket.getInputStream();
                outStream = socket.getOutputStream();
                System.out.println("Connected");
                createReadThread();
                createWriteThread();

            }
        } catch (IOException io) {
            io.printStackTrace();
        }
    }

    public void createReadThread() {
        Thread readThread = new Thread() {
            public void run() {
                while (socket.isConnected()) {
                    try {
                        byte[] readBuffer = new byte[200];
                        int num = inStream.read(readBuffer);
                        if (num > 0) {
                            byte[] arrayBytes = new byte[num];
                            System.arraycopy(readBuffer, 0, arrayBytes, 0, num);
                            String recvedMessage = new String(arrayBytes, "UTF-8");
                            System.out.println("Received message :" + recvedMessage);
                        } else {
                            notify();
                        }
                        ;
                        //System.arraycopy();

                    } catch (SocketException se) {
                        System.exit(0);


                    } catch (IOException i) {
                        i.printStackTrace();
                    }


                }
            }
        };
        readThread.setPriority(Thread.MAX_PRIORITY);
        readThread.start();
    }

    public void createWriteThread() {
        Thread writeThread = new Thread() {
            public void run() {

                while (socket.isConnected()) {
                    try {
                        BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
                        sleep(100);
                        String typedMessage = inputReader.readLine();
                        if (typedMessage != null && typedMessage.length() > 0) {
                            synchronized (socket) {
                                outStream.write(typedMessage.getBytes("UTF-8"));
                                sleep(100);
                            }
                        }/* else {
                           notify();
                       }*/
                        ;
                        //System.arraycopy();

                    } catch (IOException i) {
                        i.printStackTrace();
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }


                }
            }
        };
        writeThread.setPriority(Thread.MAX_PRIORITY);
        writeThread.start();

    }

    public static void main(String[] args) {
        ChatSocketServer chatServer = new ChatSocketServer();
        chatServer.createSocket();

    }
}

Javascript Code i used may way using javascript and html5

   function PowerPowintSend() {

var webSocket = new WrapperWS();
webSocket.send("asdasdasdasd");

}

function WrapperWS() {
    if ("WebSocket" in window) {
        var ws = new WebSocket('ws://localhost:3339');
        var self = this;

        ws.onopen = function () {
            console.log("Opening a connection...");
            window.identified = false;
        };
        ws.onclose = function (evt) {
            console.log("I'm sorry. Bye!");
        };
        ws.onmessage = function (evt) {
             console.log(evt);
        };
        ws.onerror = function (evt) {
            console.log("ERR: " + evt.data);
        };

        this.write = function () {
            if (!window.identified) {
                connection.ident();
                console.debug("Wasn't identified earlier. It is now.");
            }
            ws.send(theText.value);
        };

        this.send = function (message, callback) {
            this.waitForConnection(function () {    
                ws.send(message);
                if (typeof callback !== 'undefined') {
                  callback();
                }
            }, 1000);
        };

        this.waitForConnection = function (callback, interval) {
            if (ws.readyState === 1) {
                callback();
            } else {
                var that = this;
                // optional: implement backoff for interval here
                setTimeout(function () {
                    that.waitForConnection(callback, interval);
                }, interval);
            }
        };

        this.ident = function () {
            var session = "Test";
            try {
                ws.send(session);
            } catch (error) {
                if (error instanceof InvalidStateError) {
                    // possibly still 'CONNECTING'
                    if (ws.readyState !== 1) {
                        var waitSend = setInterval(ws.send(session), 1000);
                    }
                }
            }
        window.identified = true;
            theText.value = "Hello!";
            say.click();
            theText.disabled = false;
        };

    };

}
Amr Saied
  • 38
  • 7
  • The first thing you should do is work on your Java Server. Test it out and make sure it works first, as this will minimize possible issues when trying to connect through web sockets – ControlAltDel Apr 15 '16 at 17:40
  • I tested it using java before answer the question – Amr Saied Apr 15 '16 at 17:44

2 Answers2

0

A webSocket connection is not a generic socket connection. It runs over a TCP socket, but it connects via HTTP, then upgrades to the webSocket protocol, including exchanging some security credentials and then it speaks a specific webSocket protocol with a specific webSocket packet format.

So, you can't communicate between a webSocket from the browser and a plain socket server in Java. Instead, you will need a webSocket server on your Java end. You need a server that knows how to speak the webSocket connection sequence and protocol. There are numerous webSocket server implementations in Java. Here's one and several are mentioned in this post. I probably see the most references to people using Jetty, but I'm not a Java whiz so I don't have a specific recommendation.

To give you an idea how the webSocket protocol works, you can see Writing WebSocket Servers.

Also, this may help explain: What's the difference between WebSocket and plain socket communication?

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • i am using javascript on cross-platform application and need to connect my smart watch to java socket and i can't using anything anher javascript – Amr Saied Apr 15 '16 at 17:54
  • @عمرو السقعان - Please read my answer again. You need to fix your Java server so it properly speaks the webSocket protocol. – jfriend00 Apr 15 '16 at 17:54
-1

When open Webscoket using javacript it's send data like that

Connected
Received message :GET / HTTP/1.1
Host: localhost:3339
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: file://
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows N
Received message :T 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,ar;q=0.6
Sec-WebSocket-Key: 1udKsf4w0jKj
Received message :OC0/0uIwFQ==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Amr Saied
  • 38
  • 7
  • Yes, because just like my answer explains every webSocket connection starts with an HTTP request. If you read the references in my answer, it is all explained there. In addition, this is not an answer to your question. You could have added this to your question with the edit button, but this is not an answer. – jfriend00 Apr 16 '16 at 01:59