Socket.io not working in angular project - node.js

I am trying to learn angular with socket in a todo app. But socket is not working. I am using socket.io v2.0.3. but I am getting error in chrome console.
My code is -
import io from "socket.io-client";
private url = 'http://localhost:3001';
private socket;
ngOnInit(): void() {
this.socket = io.connect(this.url);
// Receive Added Todo
this.socket.on('TodoAdded', (data) => {
console.log('TodoAdded: '+JSON.stringify(data));
this.todos.push(data.todo);
});
}

I think you need to import io like this instead:
import * as io from 'socket.io-client';
otherwise you do not know which export to use from socket.io-client. It has
no default export.
Side Note:
You can use this.socket = io(this.url) instead of using the connect-method if you want to.

this problem sucked a lot of my energy the solution is very simple . all of you guys who are working in angular6+ and using RxJS 6+ just do this
in your polyfills.ts file just add this line
(window as any).global = window;
hope this solves your problem

Related

How can I create an HTTP server in flutter web?

I've found a lot of ways to create a server in flutter but none of them work in flutter web, only mobile. That's mainly because the dart:io package doesn't work for web and the universal_io hasn't implemented the server class. So how can I create a server?
here is an example with a dart
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
Response _echoRequest(Request request) => Response.ok('Request for "${request.url}"');
void main() async {
var handler = const Pipeline()
.addMiddleware(logRequests())
.addHandler(_echoRequest);
var server = await shelf_io.serve(handler, 'localhost', 8080);
// Enable content compression
server.autoCompress = true;
print('Serving at http://${server.address.host}:${server.port}');
}
The package https://pub.dev/packages/shelf

i want to use socket.io v4 with flutter without socket-io-client package

please guys I want another package as an alternative to socket-io-client because this package does not support nodejs socket.io version 4 and should support null safety
Try using dart:io build in package
import "dart:io";
import 'dart:typed_data';
// Client socket
void conntectToSocekt() async {
String host = "http://localhost";
int port = 3000;
Socket clientSocekt = await Socket.connect(host, port);
clientSocekt.listen((Uint8List event) {
// data comming from the socket.
});
}
the dart:io package's Socket is not support in flutter web

Unable to connect to NodeJS standalone socket.io with ReactJS

I am looking for the best WS solution for IoT project. I am currently testing my options with Web Sockets. I have tried so far two NPM libraries 'ws' and 'websockets'. They worked great both NodeJS and ReactJS implementation was simple. I am now trying websocket.io. Reading the documentation I struggle to create even a simple working example copying the code directly from the documentation. Since the test code is so simple, I am really confused especially after the positive experience with two previous packages. I am pretty sure I am doing something wrong but I am unable to spot my mistake. I am really thankful for anyone helping to spot what am I not doing right.
NodeJS server instance listening on port 8000 (based on example here: https://socket.io/docs/v4/server-initialization/) :
const io = require("socket.io")();
io.on("connection", socket => {
console.log('blip')
});
io.listen(8000);
React client trying to connect to the NodeJS server from port 2000:
import React from "react";
import { io } from "socket.io-client";
class Io extends React.Component {
state = {
wsConnected: false
}
componentDidMount() {
const socket = io.connect('http://localhost:8000');
socket.on("connect", () => {
console.log('connect',socket.id);
});
}
render() {
const { wsConnected } = this.state;
return (
<div>{wsConnected ? 'on' : 'off'}</div>
)
}
}
export default Io
It seems you have CORS problem when in polling transport mode, So you can use Socket.io standalone server like this when you are using polling:
const io = require("socket.io")(
{
cors: {
origin: '*',
}
}
);
io.on("connection", socket => {
console.log(`${socket.handshake.headers.origin} connected`);
});
io.listen(8000);
But it's better use websocket transport if you need persistent http connection. When you are using websocket transport mode, there's no CORS policy.
websocket transport doesn't support http headers like cookies or etc but it is better to use it when there's energy consumption concerns in client side. Also you can force socket.io server to only supports determined transport modes. See socket.io documentations.

Error on creating socket server with socket.io on typescript

Im new at socket io and im trying to use typescript on the project so i got the error of the image on start the socket server, i already tried to change the import to import * as socketIo from 'socket.io' but nothing changes, i dont know if is some version issue or im doing something wrong.
the error:
code:
Type declaration for socket.io does not contain default export. You can check it in its index.d.ts. It contains the following:
export { Socket, ServerOptions, Namespace };
That's why to init socket.io server object you need to use the following instruction:
const app = express();
const httpServer = new http.Server(app);
const io = new socketio.Server(httpServer);

Cassandra with react, net.socket error

I am a newwbie to react and cassandra. I am just trying to connect to the cassandra db by using "npm i cassandra-driver".
I am having a main.js file where I used the cassandra driver code.
Main.js
import 'babel-polyfill';
import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import FastClick from 'fastclick';
import { Provider } from 'react-redux';
import store from './core/store';
import router from './core/router';
import history from './core/history';
const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['127.0.0.1'], keyspace: 'excelsior'});
console.log("client---->",client);
const query = 'SELECT * FROM playlists';
client.execute(query, [], function(err, result) {
console.log("err----->",err);
console.log("result----->",result);
assert.ifError(err);
//console.log('got user profile with email ' + result.rows[0].email);
});
let routes = require('./routes.json'); // Loaded with utils/routes-loader.js
const container = document.getElementById('container');
function renderComponent(component) {
ReactDOM.render(<Provider store={store}>{component}</Provider>, container);
}
// Find and render a web page matching the current URL path,
// if such page is not found then render an error page (see routes.json, core/router.js)
function render(location) {
router.resolve(routes, location)
.then(renderComponent)
.catch(error => router.resolve(routes, { ...location, error }).then(renderComponent));
}
continued code ......
I am getting the client console, But After that i am getting an error like
connection.js:122 Uncaught TypeError: net.Socket is not a constructor(…)
Am I missing something here. or is this piece of code should be written anywhere else. ?
Thanks
The cassandra-driver is meant to be run on a Node.js server, not in the client (i.e. browser).
So, you'll need to create a Node.js server of some kind for your client code (using React, Redux, or whatever) to talk to. For example, in a typical web application setup, your client code in the browser will:
make an HTTP call to the server
the server will process that call and use the cassandra-driver to go get the appropriate data for that call
then send the appropriate data back to the client in the HTTP response
This is a pretty gross simplification of how things could be setup, but this type of communication is common for many web applications, regardless of whether they're using Cassandra, Postgres, or whatever database on the server.

Resources