uNetworking / uWebSockets.js

μWebSockets for Node.js back-ends :metal:
Apache License 2.0
8.09k stars 577 forks source link

uncaughtException: TypeError: res.onData is not a function #687

Closed nicolasguasca1 closed 2 years ago

nicolasguasca1 commented 2 years ago

Im migrating this server configuration to a Socket.io setup in which you can see use uWebSockets.js for the http server under the hood. The commented lines are the previous state (which works perfectly):


`// import express, { Express, Request, Response } from "express";
// import * as http from "http";
import * as uWebSockets from "uWebSockets.js";
import expressify from "uwebsockets-express";
import next, { NextApiHandler } from "next";
import * as socketio from "socket.io";
import SocketManager from "./SocketManager";

import allowCors from "../pages/api/cors";
import dotenv from "dotenv";

dotenv.config();
const port: number = parseInt(process.env.SERVER_PORT || "5000", 10);
const dev: boolean = process.env.NODE_ENV !== "production";
export const nextApp = next({ dev });
const nextHandler: NextApiHandler = nextApp.getRequestHandler();

nextApp.prepare().then(async () => {
  // const app: AppOptions = express();
  const app: uWebSockets.TemplatedApp = uWebSockets.App();
  const myapp = expressify(app);
  // const server: http.Server = http.createServer(app);
  const io: socketio.Server = new socketio.Server({
    cors: {
      origin: "*",
      methods: ["GET", "POST"]
    }
  });

// io.attach(server);
  io.attachApp(app);

  myapp.get("/", async (_, res) => {
    res.send("Running");
  });

  myapp.use("../pages/api/cors", allowCors);
  io.on("connection", SocketManager);

  myapp.all("*", (req: any, res: any) => nextHandler(req, res));

  myapp.listen(port, () => {
    console.log(
      `> Server listening at http://localhost:${port} as ${
        dev ? "development" : process.env.NODE_ENV
      }`
    );
  });
});`

Here is a SocketManager.ts file that contains all the processes undertaken by the socket:

`import * as socketio from "socket.io";

const io: socketio.Server = new socketio.Server({
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

export default function SockerManager(socket: socketio.Socket) {
  try {
    socket.emit("me", socket.id);

    socket.on("disconnect", () => {
      socket.broadcast.emit("callEnded");
    });

    socket.on("callUser", ({ userToCall, signalData, from, name }) => {
      io.to(userToCall).emit("callUser", { signal: signalData, from, name });
    });

    socket.on("answerCall", (data) => {
      io.to(data.to).emit("callAccepted", data.signal);
    });
  } catch (ex) {
    console.log(ex);
  }
}`

And this is the CORS middleware:

import Cors from "cors";
import initMiddleware from "../../lib/init-middleware";
import { Request, Response } from "express";

// Initializing the cors middleware
const cors = initMiddleware(
  Cors({
    origin: "*",
    methods: ["GET", "POST", "OPTIONS"],
  })
);

export default async function allowCors(req: Request, res: Response) {
  // Run cors
  await cors(req, res);

  // Rest of the API logic
  res.json({ message: "Cors responding here!" });
}

I can't think of anything that's missing. I've been trying to replace express parameters on the CORS documents for the uWebSockets methods without success. If you have any ideas they will be much appreciated.

Cheers!

ghost commented 2 years ago

Well that's just horrible and you've completely missed the whole point of this project.

nicolasguasca1 commented 2 years ago

Thank you for your reply @alexhultman. Can you point me to where I can find in this project's documentation a way to implement uwebsockets with NEXTJS. Now that you have seen my code, do you think there is something in your docs I can use to translate it?

totaland commented 2 years ago

Just implement the uwebsocketjs as it own server. Maybe don’t use nextjs api. Just use nextjs as static web. Then deploy the server with docker. I haven’t done it. Just think that might be what Alex mean.

On Tue, 18 Jan 2022 at 23:35, Nicolás Guasca @.***> wrote:

Thank you for your reply @alexhultman https://github.com/alexhultman. Can you point me to where I can find in this project's documentation a way to implement uwebsockets with NEXTJS. Now that you have seen my code, do you think there is something in your docs I can use to translate it?

— Reply to this email directly, view it on GitHub https://github.com/uNetworking/uWebSockets.js/issues/687#issuecomment-1015418490, or unsubscribe https://github.com/notifications/unsubscribe-auth/AIWOHAZ27ITOCHDLRK33BTTUWVUDPANCNFSM5MHC6QVQ . You are receiving this because you are subscribed to this thread.Message ID: @.***>

--

James Nguyen

Master of Information Technology – UQ

M: 0434538803

@.***> http://www.linkedin.com/in/jamesnguyen868

ghost commented 2 years ago

Express and Socket IO are the worst two projects ever created by man. So shoehorning uws into both of those is completely pointless and circumvents the entire point of this project

e3dio commented 2 years ago

@nicolasguasca1 You are taking 3 things that are incompatible with uWebSockets.js (Express,js, Socket.io, Next.js) and trying to combine them all together. If you want best performance you should get rid of those and code server with uWebsockets.js, it's not hard. But for this issue you are trying to use that uwebsockets-express library so really you should be opening issue over there not here. But you can see there is no activity over there because there is no point to that library because they are not compatible and you lose performance

nicolasguasca1 commented 2 years ago

Thank you so much @e3dio @alexhultman for your comments. I spent my day checking at the uWebSockets.js docs and I want to start with the following:

import * as uWebSockets from "uWebSockets.js";

dotenv.config();
const port: number = parseInt(process.env.SERVER_PORT || "5000", 10);
const dev: boolean = process.env.NODE_ENV !== "production";

const app = uWebSockets
  .App()
  .ws("http://localhost", {
    idleTimeout: 30,
    maxBackpressure: 1024,
    maxPayloadLength: 512,
    compression: uWebSockets.DEDICATED_COMPRESSOR_3KB,
    open: (ws) => {
      let ip = ws.getRemoteAddressAsText();
      console.log("Connection opened and started from" + ip);
    },
    close: (ws, code, reason) => {
      console.log("Connection forcefully closed: " + code + " " + reason);
    },
    message: (ws, message, isBinary) => {
      console.log("Message: " + message);
      let ok = ws.send(message, isBinary, true);
    }
  })
  .get("/", (res, req) => {
    res
      .writeStatus("200 OK")
      .writeHeader("Access-Control-Allow-Origin", "*")
      .end("Running awesome!");
  })
  .any("/*", (res, req) => {
    res.end("Nothing to see here!");
  })
  .listen(port, (listenSocket) => {
    if (listenSocket) {
      console.log(
        `> Server listening at http://localhost:${port} as ${
          dev ? "development" : process.env.NODE_ENV
        }`
      );
    }
  });

However, when using nodemon to restart the server it stands by without response: [nodemon] starting `ts-node --project tsconfig.server.json server/index.ts index.js` [nodemon] spawning [nodemon] child pid: 58621 [nodemon] clean exit - waiting for changes before restart

Is there anything else I might be missing to have a working socket? The next step would be to deploy this socket on docker or something like that which I can use to feed my front-end, am I right? I'm trying to build a video conferencing meet/zoom like prototype so all the information you can provide will be much appreciated.

e3dio commented 2 years ago

Looks like it did not listen to the port, it did not log the "Server listening" so make sure it is listening to a valid open port, log the port before listening and check if anything else using port. This is not related to the original issue so you should close this issue and open Discussion if you have Q&A questions

nicolasguasca1 commented 2 years ago

I've checked an implementation to modify my code. Thank you all for the guidance. Although it was challenging to get into the docs and try to change the chip to uWebSockets, it was nice to see the interest to help and bring solutions to the table. I personally admire projects for the people behind them rather than the mere technology.

Keep up with the great work!