3

I am trying to send a message to my node.js/socket.io server via Java

Here is the code i am using to send the message

import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

class socketMessage {

    public socketMessage() {
    }

    public static void send(String string) throws Exception {
        System.out.println("Sending message to Socket Server!");

        URL url = new URL("http://<mysite>:8000");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        try (OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) {
            System.out.println("Data Sent!");
            writer.write(string);
            writer.flush();
        }
        conn.getResponseCode(); // Thanks to BGR
    }
}

called with: socketMessage.send("Admin|notification|Logged in elsewhere\n> Official Java App");

and here is the server code:

var http = require("http");
var io = require('socket.io');

var sessionsConnections = {};
var whereIsUserVisitingFrom = {};

console.log("\n\n-------------------------------- Server Started --------------------------------");

var server = http.createServer(function(req, res){ 
    var body = '';
    req.on('data', function(data){
        console.log('Received Data');
        body += data;
    });
    req.on('end', function() {
        // Emit the data to all clients
        ioServer.emit('message', { message: body });
    });
});
server.listen(8000);

var ioServer = io.listen(server, { log: false });

ioServer.on('connection', function(socket) {

    var currentUser;

    var parts;

    socket.on('started', function(data) {
        currentUser = data.username;
        sessionsConnections[currentUser] = socket.id;
        whereIsUserVisitingFrom[currentUser] = data.from;
        socket.emit("connected", { message: "Welcome, " + currentUser + "!" });

        socket.broadcast.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
        socket.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
    });

    socket.on('message', function(data) {
        var parts = data.message.split("|");

        socket.broadcast.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
        socket.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });

        console.log("Message Recieved!");

        if( parts[0] == "*" ) {
            socket.broadcast.emit("display", { message: data.message });
        }else{
            if( parts[0] in sessionsConnections ) {
                io.sockets.socket(sessionsConnections[parts[0]]).emit("display", { message: data.message });
            }else{
                socket.emit("display", { message: "That user is not online!" });
            }
        }
    });

    socket.on('disconnect', function() {
        delete sessionsConnections[currentUser];
        socket.broadcast.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
        socket.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
    });

});

basically what my server does currently is when I visit my website, then send a command from my Admin Center in the form of "{user}|{action (i.e. notification)}|{text/extra_param(s)}" it will send a message to the client of whom you set as the {user} and then I have code on the client side that splits that message into parts and changes the websites UI accordingly, but I also want to do this from my Java app, and it ain't working :(

any ideas

Vinny

Thanks in advance

2
  • can you define "not working"? error? timeout? ...?? Commented Jan 20, 2013 at 21:45
  • The server just isnt recieving the data, I have my server writing to the console everytime it receives data, I don't know how I would check for errors or timeouts, I'm guessing they would show up on the java client side in the Netbeans output console, if so there are no errors/timeouts displaying Commented Jan 20, 2013 at 21:59

2 Answers 2

1

To complete the HTTP connection, the HTTP response must be read.

Insert conn.getResponseCode() after the try block

Sign up to request clarification or add additional context in comments.

5 Comments

I added this, but my node server is not receiving the message :/
@MRVDOG What is the value of conn.getResponseCode()?
conn.getResponseCode() returns '200'
@MRVDOG Your server did receive a connection an replied. Run a debugger server side, your client looks fine or is not sending any content
okay I will do, I have work now, so will try when I get home, thanks for your help. I will let you know how it goes
0

After add

conn.getResponseCode()

still not make this work. Finally I found socket.io-java-client exactly what we need。Because socket.io not use orginal websocket which you use but add a protocl on it, and your code "data" event will never triggered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.