I'm trying to create a simple Websocket connection in my project.
Java code:
#ServerEndpoint("/echo")
public class EchoEndpoint {
#OnMessage
public void onMessage(Session session,String message){
try{
System.out.println(message);
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
html and javascript code:
<button type="button" onclick="WebSocketTest()">Send</button>
<script type="text/javascript">
function WebSocketTest()
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:8080/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
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...");
};
}
</script>
after pressing the button I got the errorWebSocket connection to 'ws://localhost:8080/echo' failed: Error during WebSocket handshake: Unexpected response code: 404
Jboss Wildfly8 is used as Application Server.
Any Idea? or any working example?
This is because you put wrong path here:
var ws = new WebSocket("ws://localhost:8080/echo");
if your application is packed to eg: websocketapp.war (or if you set context-path on websocketapp)
then you should use:
var ws = new WebSocket("ws://localhost:8080/websocketapp/echo");
Connecting to web-socket For example
var webSocket= new WebSocket("ws://l92.168.1.27:50333/project name//serverendpointdemo");
var messagesTextArea=document.getElementsByClassId("messagesTextArea");
webSocket.onopen=function(message){processOpen(message);};
webSocket.onclose=function(message){processClose(message);};
webSocket.onmessage=function(message){processMessage(message);};
webSocket.onerror=function(message){processError(message);};
function processOpen(message){
messagesTextArea.value+="Server connected...."+"\n";
}
function processMessage(message){
messagesTextArea.value+="Received from server:...."+message.data+"\n";
}
Related
I am trying to connect my android app to NodeJS server.
ANDROID PART
First I include the Socket.io library to my dependency
implementation('io.socket:socket.io-client:2.0.0') {
exclude group: 'org.json', module: 'json'
}
My JAVA code
//all variables used are initialized, defined and working perfectly
try {
socket = IO.socket(socketUrl);
socket.on(Socket.EVENT_CONNECT, args -> runOnUiThread(() -> socket.emit("connected", true)));
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
SERVER SIDE
var express = require('express'),
app = express(),
socket = require('socket.io'),
router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var server = app.listen(4000, function(){
console.log('listening for requests on port 4000,');
});
let io = socket(server);
io.on('connection', function(socket){
console.log(`${socket.id} is connected`);
});
module.exports = router;
Now the problem is after starting the Server, and I try to connect my android app to it, I keep getting an error from Socket.io connection, like the image below
I have searched SO for solution and I get multiple answers relating to this, but I still keep getting the same error
My Socket.io version is 8.5.5
you can not use socket directly via express, here is the documentation.
try this code instead.
var express = require('express'),
app = express()
const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpServer);
router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
io.on('connection', function(socket){
console.log(`${socket.id} is connected`);
});
httpServer.listen(4000, function(){
console.log('listening for requests on port 4000,');
});
module.exports = router;
I'm trying to connect my android app to a nodeJS server using Socket.io
this is the connection code from android:
final String URL = "http://192.168.0.103:3000";
try {
mSocket = IO.socket(URL);
mSocket.connect();
mSocket.emit("message", "Hello");
Toast.makeText(MainActivity.this, "Socket Connected!!",Toast.LENGTH_SHORT).show();
} catch (URISyntaxException e) {
e.printStackTrace();
}
nothing more on android, also I have my internet permission added to manifest and I'm using next library:
implementation 'com.github.nkzawa:socket.io-client:0.6.0'
On the server-side, I'm using also Socket.io library, but for nodeJS and the connection is made like in following lines of code:
const app = express();
app.set("port", process.env.PORT || 3000);
let http = require("http").Server(app);
let io = require("socket.io")(http);
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Content-Type", "application/json");
next();
});
app.get("/", (req: any, res: any) => {
res.send("hello world");
});
io.on("connection", function(socket: any) {
console.log("a user connected");
// whenever we receive a 'message' we log it out
socket.on("message", function(message: any) {
console.log(message);
});
});
const server = http.listen(3000, function() {
console.log("listening on *:3000");
});
When I'm trying to connect from android any line of code is executed with success, even the Toast message, but on server nothing. Also, I made a little script on nodeJS using "socket.io-client" library, for testing where I'm trying to connect to the same server and all the stuff is working fine, the connection is created with success, I receive the message on the terminal from the server, and from the script also I have a success message. the following script looks like this:
var io = require("socket.io-client");
function checkSocketIoConnect(url, timeout) {
return new Promise(function (resolve, reject) {
var errAlready = false;
timeout = timeout || 5000;
var socket = io(url, { reconnection: false, timeout: timeout });
// success
socket.on("connect", function () {
clearTimeout(timer);
resolve();
socket.close();
});
// set our own timeout in case the socket ends some other way than what we are listening for
var timer = setTimeout(function () {
timer = null;
error("local timeout");
}, timeout);
// common error handler
function error(data) {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (!errAlready) {
errAlready = true;
reject(data);
socket.disconnect();
}
}
// errors
socket.on("connect_error", error);
socket.on("connect_timeout", error);
socket.on("error", error);
socket.on("disconnect", error);
});
}
checkSocketIoConnect("http://192.168.0.103:3000").then(function () {
// succeeded here
console.log("working");
}, function (reason) {
// failed here
console.log("why not: ", reason);
});
I need to connect a client TCP created in java with a HTTP server created with node.js
I want that on having done click on a button of my HTML an operation executes in the client java via sockets using the module net.
My code HTML:
<body>
<button id="bt1">Button 1</button>
<button id="bt2">Button 2</button>
<button id="bt3">Button 3</button>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('httpServer', function (data) {
console.log(data);
socket.emit('tcp', "For TCP");
});
</script>
</body>
My code java client:
class ClientSocket{
public static void main(String[] args){
String address = "127.0.0.1";
int port = 5555;
try {
Socket socket = new Socket(address, port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ope = in.readLine();
if(ope.equals("1")){
System.out.println("You pulsated on the button 1");
}else if(ope.equals("2")){
System.out.println("You pulsated on the button 2");
}else if(ope.equals("3")){
System.out.println("You pulsated on the button 3");
}
// ........
in.close();
socket.close();
}catch( IOException e){
System.out.println(e);
}
}
}
My code node serverTCP.js:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 5555;
var server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.write("TCP sending message : 1"); // No send
console.log('Server listening on ' + server.address().address +':'+ server.address().port);
}).listen(PORT, HOST);
My code node serverHTTP.js:
var http = require('http').createServer(httpHandler), fs = require("fs"), wsock = require('socket.io').listen(http), tcpsock = require('net');
var http_port = 8080;
var tcp_HOST = '127.0.0.1';
var tcp_PORT = 5555;
/**
* http server
*/
function httpHandler (req, res){
fs.readFile(__dirname + '/index.html',
function(err, data) {
if(err){
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
http.listen(http_port);
console.info("HTTP server listening on " + http_port);
wsock.sockets.on('connection', function(socket){
var tcpClient = new tcpsock.Socket({allowHalfOpen: false, readable: true, writable: true});
tcpClient.setEncoding("ascii");
tcpClient.setKeepAlive(true);
tcpClient.connect(tcp_PORT, tcp_HOST, function(){
console.info('CONNECTED TO : ' + tcp_HOST + ':' + tcp_PORT);
tcpClient.on('data', function(data){
console.log('DATA: ' + data);
socket.emit("httpServer", data);
});
tcpClient.on('end', function(data){
console.log('END DATA : ' + data);
});
});
socket.on('tcp-manager', function(message){
console.log('"tcp" : ' + message);
return;
});
socket.emit("httpServer", "Initial Data");
});
Better use a http server for that. Use Tomcat and create a simple Servlet will fix your problem.
Otherwise you need to listen on the port and accept incoming requests using separate tasks. Thats more complex then your sample code. See http://www.oracle.com/technetwork/java/socket-140484.html
I want to implement a java server and a php client. Every time a click is done on the website (php client) a action should be executed on the server.
Actually my server looks like:
public static void main(String args[]) {
System.out.println("Signal Server is running.");
try {
socket = new ServerSocket(port);
while (true) {
connection = socket.accept();
InputStreamReader inputStream = new InputStreamReader(connection.getInputStream());
DataOutputStream response = new DataOutputStream(connection.getOutputStream());
BufferedReader input = new BufferedReader(inputStream);
command = input.readLine();
response.writeBytes(responseStr);
response.flush();
System.out.println("Running");
}
} catch (IOException e) {
System.out.println("Fail!: " + e.toString());
}
System.out.println("Closing...");
}
My HTML site looks like:
<?php
if (isset($_POST["Btn1"])){
$address = "localhost";
$port = 4343;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$message = 'blablabla';
socket_connect($socket, $address, $port);
socket_sendto($socket, $message, strlen($message), 0, $address, $port);
};
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<form id="form1" method="POST">
<button type="submit" form="form1" id="Btn1" name="Btn1" value="Btn1" title="Btn1">
Btn1</button>
</form>
</body>
</html>
My problem is, whats the best way to delegate the actions to the server. A little example, I have a method on my java server which posts "Hello" to the console. Now I click on a button on my website and this method should be executed. What is the best way to do?
Can I use my approach or is there a better one?
PHP runs server-side, so you cannot execute PHP code on the client's web page...
Im trying to connect from a Java client i am writing to my nodejs sockjs server.
The sockjs server is just a simple echo server, taken from the examples on git:
var http = require('http');
var sockjs = require('sockjs');
var node_static = require('node-static');
// 1. Echo sockjs server
var sockjs_opts = {sockjs_url: "http://cdn.sockjs.org/sockjs-0.3.min.js"};
var sockjs_echo = sockjs.createServer(sockjs_opts);
sockjs_echo.on('connection', function(conn) {
conn.on('data', function(message) {
conn.write(message);
});
});
// 2. Static files server
var static_directory = new node_static.Server(__dirname);
// 3. Usual http stuff
var server = http.createServer();
server.addListener('request', function(req, res) {
static_directory.serve(req, res);
});
server.addListener('upgrade', function(req,res){
res.end();
});
sockjs_echo.installHandlers(server, {prefix:'/echo'});
console.log(' [*] Listening on 0.0.0.0:8080' );
server.listen(8080, '0.0.0.0');
Now i've tried to connect from my Java client with the following:
public static void connect() throws Exception {
final WebSocket ws = new WebSocket();
ws.addWebSocketListener(
new WebSocketAdapter() {
#Override
public void onMessage(WebSocketEvent messageEvent) {
System.out.println("Received Event Data: " + messageEvent.getData());
// let's close the open connection...
try {
ws.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onOpen(WebSocketEvent openEvent) {
System.out.println("Connection to Server is up!");
// we are able to talk to the WebSocket gateway
try {
ws.send("Hey, server!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
);
ws.connect(new URI("ws://server.hello.com:8080/echo/websocket"));
}
The error i am getting when my java client tried to connect is:
com.kaazing.gateway.client.html5.impl.bridge.BridgeUtil
initCrossOriginProxy WARNING: Unable to connect: the Gateway may not
be running, a network route may be unavailable, or the Gateway may not
be configured properly
Any ideas what could be wrong?