48 lines
		
	
	
		
			989 B
		
	
	
	
		
			JavaScript
		
	
	
	
			
		
		
	
	
			48 lines
		
	
	
		
			989 B
		
	
	
	
		
			JavaScript
		
	
	
	
| const httpServer = require("http").createServer();
 | |
| const io = require("socket.io")(httpServer, {
 | |
|   cors: {
 | |
|     origin: "*",
 | |
|   },
 | |
|   // config
 | |
| });
 | |
| 
 | |
| io.on("connection", (socket) => {
 | |
|   try {
 | |
|     // JOIN
 | |
|     socket.on("join", (data) => {
 | |
|       console.log({
 | |
|         info: "Socket was join to room",
 | |
|         join: data,
 | |
|         id: socket.id,
 | |
|       });
 | |
|       socket.join(data.join);
 | |
|     });
 | |
| 
 | |
|     // MESSAGE
 | |
|     socket.on("message", (data) => {
 | |
|       console.log({
 | |
|         info: "Received from client",
 | |
|         data: data,
 | |
|         id: socket.id
 | |
|       });
 | |
|       // handle message
 | |
|       if (data?.to) {
 | |
|         socket.join(data.to);
 | |
|         socket.broadcast
 | |
|           .to(data.to)
 | |
|           .emit('message', data);
 | |
|       } else {
 | |
|         io.emit('message', data);
 | |
|       }
 | |
|     });
 | |
|   } catch (error) {
 | |
|     console.error(error);
 | |
|   }
 | |
| });
 | |
| 
 | |
| const port = process.env.PORT || 3000;
 | |
| const host = "0.0.0.0";
 | |
| httpServer.listen(port, host, () => {
 | |
|   console.log(`Server running on port ${host}:${port}`);
 | |
| });
 |