Android app does not connect via socket.io, but via browser everything is fine. If I access via browser http://localhost:3000, it works, but when I run the android app nothing happens and there is no error message either. Note: I am using nodejs.
MainActivity.java
package com.security.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
public class MainActivity extends AppCompatActivity {
public Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I created a ddns domain for external access directing to the nodejs
server port 3000
try {
socket = IO.socket("http://my_domain_ddns:3000");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
node.js
const express = require('express');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'public'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use('/', (req, res) => {
res.render('index.html');
});
io.on('connection', socket => {
console.log(`Socket conectado: ${socket.id}`);
});
server.listen(3000);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="with=device-with, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Chat</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.js"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form id="chat">
<input type="text" name="username" placeholder="Digite seu usuario">
<div class="messages"></div>
<input type="text" name="message" placeholder="Digite sua mensagem">
<button type="submit">Enviar</button>
</form>
<!-- Fazendo a conexao do front com o socket -->
<script type="text/javascript">
var socket = io('http://my_domain_ddns:3000');
</script>
</body>
</html>
I have corrected the url in index.html
var socket = io('http://my_domain_ddns:3000');
Change localhost in your android by the public IP of your router.
Do a port forwarding from your router to your server.
Check that your server has the port where you do your forwarding is open.
This video video give more explanation.
Well, I found another way that worked.
private void initiateSocketConnection() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(SERVER_PATH).build();
webSocket = client.newWebSocket(request, new SocketListener());
}
build.grade
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
Related
im trying to implement a chat client, i think my client server communication work, because i receive the messages in different tabs. im using a https connection
im getting in chrome following error:
WebSocket connection to 'wss://localhost/socket.io/?EIO=4&transport=websocket&sid=B-vRFkxNxHPkiK6cAAAE' failed: websocket.js:54
in firefox:
Firefox can’t establish a connection to the server at wss://localhost/socket.io/?EIO=4&transport=websocket&sid=vSwzZh9BE3cpHZHPAAAC.
im using a self signed certificate, that i created with openssl, thats why i get follwing konsole log in chrome:
This site does not have a valid SSL certificate! Without SSL, your site's and visitors' data is vulnerable to theft and tampering. Get a valid SSL certificate before releasing your website to the public.
server.js:
const express= require('express')
const app= express();
const https= require('https')
const fs=require('fs')
const PORT=process.env.PORT || 443
const httpsOptions={
key: fs.readFileSync('cert/key.pem'),
cert: fs.readFileSync('cert/cert.pem')
}
var server=https.createServer(httpsOptions,app);
server.listen(PORT,function(){
console.log(`listening to port ${PORT}`)
})
const io = require('socket.io')(server,{maxHttpBufferSize:1e8}).listen(server)
app.get('/test', (req,res)=>{
res.sendStatus(200);
})
app.use(express.static(__dirname + '/public'))
app.use(require('./routes/posts'));
app.use(require('./routes/users'));
//app.use(require('./public/client'));
app.get('/',(req,res)=>{
res.sendFile(__dirname + '/login_register/login.html')
})
app.get('/register',(req,res)=>{
res.sendFile(__dirname + '/login_register/register.html')
})
app.get('/chatroom',(req,res)=>{
res.sendFile(__dirname + '/index.html')
})
io.on('connection',(socket)=>{
console.log('new connection',socket.id)
socket.on('message', (msg)=>{
socket.broadcast.emit('message',msg)
})
socket.on('file-message', (msg)=>{
socket.broadcast.emit('file-message',msg)
})
})
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/style.css">
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
</head>
<body>
<section class="chat_section">
<div class="brand">
<img src="" alt="">
<h1> chat</h1>
</div>
<div class="message_area">
</div>
<div>
<textarea id="textarea" cols="30" rows="1" placeholder="write a message "></textarea>
</div>
<input type="file"id="fileupload" name="fileName">
<button id="submitFile" onclick="submitData()">senden</button>
</section>
<script>
socket = io('https://localhost:443/')
//also testet:
//const socket=io()
//didnt worked
let userName;
let userName_;
//const textarea = document.getElementById('textarea')
let textarea=document.querySelector('#textarea')
let messageArea= document.querySelector('.message_area')
let file__ = document.querySelector('#fileupload')
userName=sessionStorage.getItem('displayUsername')
userName_= userName
console.log(userName_)
sessionStorage.removeItem('displayUsername');
sessionStorage.clear();
//console.log(userName_)
if(userName_==null){
alert("dont scam")
window.location.href = '/'
}
//console.log(localStorage.getItem(displayUsername));
textarea.addEventListener('keyup', (e)=>{
if(e.key === 'Enter'){
sendMessage(e.target.value)
}
})
function sendMessage(message){
let msg= {
user:userName_,
message:message.trim()
}
//append message to frontend call function
appendMessage(msg,'outgoing')
textarea.value=""
scrollBottom()
//send to server
socket.emit('message', msg)
}
function appendMessage(msg,type,isFile){
//dont needed to understand
}
//recive messages
socket.on('message',(msg)=>{
//console.log(msg)
appendMessage(msg,'incoming')
scrollBottom()
})
socket.on('file-message',(msg)=>{
console.log(msg)
//File name Here
let message={
message: msg.filename,
user: msg.user,
result: msg.result
}
//send to the others
appendMessage(message,'incoming',isFile=true)
})
function scrollBottom(){
messageArea.scrollTop=messageArea.scrollHeight
}
function submitData(){
//dont needed to understand
}
}
function downloadFile(result,filename){
//dont needed to understand
}
</script>
</body>
</html>
I have below folder structure in VS2015:
The server.js has below code:
var express = require('express')
var app = express();
var http = require('http').Server(app);
var path = require('path');
var port = process.env.port || 1337;
app.use(express.static(__dirname + 'client'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,'client', 'HTML1.html'));
});
http.listen(port, function () {
console.log(`listning on ${port}`);
})
and Html1.Html has below code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head data-ng-app="imageLoaderApp">
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
</div>
<script src="/client/scripts/angular.js"></script>
<script type="text/javascript">
var app = angular.module('imageLoaderApp', []);
app.controller('loadController', function ($scope) {
console.log(`i'm here.'`);
});
</script>
</body>
</html>
When I'm hitting below url in browser
http://localhost:1337/
I'm getting below error in console:
This is happening with all the js files. I even tried to move the html and js files in main folder still getting the same error.
What am I doing wrong?
It looks like HTML1.html is in the client folder. If that is the case I think you need to put the path to the js relative to it so: 'src="scripts/angular.js"'
I have a web service and a node project with a html page. I want to sends get request from my node project to my web service and in the return of web service i want to print that "hello world" on my website.
My web service.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello World";
}
}
My Node project:
var express=require('express');
var http = require('http');
var https = require("https");
var request=require("request");
var app=express();
app.get('/',function(req,res){
res.sendfile('index.html');
});
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});
app.get('/this',function(req,res){
request
.get('http://localhost:8080/ConnectingToNode/webapi/myresource')
.on('response', function(response) {
console.log(response.statusCode); // 200
console.log(response.headers['content-type']);
var a=response.toString();
console.log(a);
});
});
module.exports = app;
My index.html
<!DOCTYPE html>
<html>
<head>
<title>TO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function This(){
window.open("http://localhost:8080/ConnectingToNode/webapi/myresource");
}
</script>
<button onclick="This()" type="button">Click Me!</button>
</body>
</html>
I am new to NodeJS and socket.io. I just intend to detect a socket connected to the Express server. It was working fine for me when I was not using Express server.
Then for some reason I used Express and wanted everything to be static so I added this line to the Server File.
app.use(express.static(__dirname));
The above line disturbs my client.html file. Below is the code for my client.html. I debugged it using developer console and found that the script src containing "/socket.io/socket.io.js" is not valid.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="/socket.io/socket.io.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="/css/style.css"/>
<title>Untitled Document</title>
<script>
var socket = io.connect();
socket.on('connect',function(){
console.log("socket.io working");
});
</script>
</head>
</html>
What concept or thing am I missing?
For more info: This is my directory structure of the application.
-MyChatRoom
--ChatServer.js
--html
----client.html
--css
----style.css
--images
--node_modules
----socket.io
----express
Edited
For better understanding here is my ChatServer.js code
fs = require('fs');
url = require('url');
express = require('express');
app = express();
server = require('http').createServer(app);
socketio = require('socket.io')(server);
//The root and all subs are made static
app.use(express.static(__dirname));
app.get('/',function(request,response){
response.sendFile(__dirname + "/html/index.html");
});
app.listen(3000);
var connectedUsers = 0;
socketio.on('connection',function(socket){
connectedUsers++;
console.log('client connected');
});
app.listen(3000);
should be
server.listen(3000);
You need to listen on the http module not the express one.
Express is passed through the http module when you instantiate it. Socket.io uses the http module, this is why you need to listen on this to get it to work.
I am new to Node.js.
I have my NodeServer.js file which has below code.
var express = require("express");
var app = express();
var port = 60000;
var io = require('socket.io').listen(app.listen(port));
console.log("Listening on port " + port);
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
When I run this from command prompt , by below code
D:\Path to my application>Node NodeServer.js
It shows message like
info - socket.io started
Listening on port 60000
But when I try to connect to this port from browser by http://127.0.0.1:60000, it shows me below error in command prompt
D:\Path to my application\node_modules\expres
s\lib\application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot call method 'handle' of undefined
What am I Doing wrong?
Above issue is solved:
Below is my EDIT
Below is my client Script
$(document).ready(function () {
var socket = io.connect('http://127.0.0.1:60000');
});
Below is my desing
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="http://127.0.0.1:60000/socket.io/socket.io.js" type="text/javascript"></script>
<script src="NodeClient.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
When I run my application I get error of "NetworkError: 404 Not Found - http://127.0.0.1:60000/socket.io/socket.io.js"
I have solved my issue by below steps.
I moved my ClientScript to one specific folder(Scripts).(Say my client Script's name is NodeClient.js)
I removed app.get("/", function(req,res){ your logic should go here }); function from Server script.
added below code app.use(express.static(__dirname + '/Scripts'));
Now it is working the way I want.
I don't know whether it is right way or not, but it is working now for me.
change the following line
var io = require('socket.io').listen(app.listen(port));
by
var io = require('socket.io').listen(port);
app.listen(port) returns an object but we have to run the socket.io and express in same port. To do that simply pass the port variable