🔍

basic socket server chat system in p5 js


let socket = io("https:// .me");
 

function setup() {
  
  createCanvas(window.innerWidth,window.innerHeight);
	
  setupSockets(12000, 3334);
  background(0, 0, 255);

}

function draw() {
  
}


function sendOsc(address, value) {
	socket.emit('sendData', [address].concat(value));
    
}

function sendData(datatype, data) {
  data.type = datatype;
  socket.emit("send_data", data);
}



function setupSockets(oscPortIn, oscPortOut) {
  
  //socket = io.connect(URL);
 // socket.on("get_data", onReceiveData);
  socket.on("broadcast_data",  onReceiveData); 
  
  
  
}

function onReceiveData(e){
  
  let _cx = e.x * width;
  let _cy = e.y * height;
  noStroke();
  ellipse(_cx,_cy,12,12);
  textSize(8);
  fill(255);
  text(e.name,_cx+8,_cy+4);

}

function mousePressed(){


    
  let data = {
        
         id:socket.id,
        name:"penis",//socket.id,
        x:mouseX/width,
        y:mouseY/height
        
      };
  // console.log(socket.id);
   // sendData("send_data", data);

   // console.log("trysend");
  socket.emit("send_data", data);
  
  
   
  noFill();
  stroke(255);
  ellipse(data.x*width,data.y*height,12,12);
}

 



// some simple arrays to collect active users
var clients = []; 
let clientids = []; 

//create server
let port = process.env.PORT || 8000;
let express = require('express');
let app = express();
let server = require('http').createServer(app).listen(port, function(){
  
  console.log('Socket Server is listening at port: ', port);
  
});

//create socket connection
let io = require('socket.io').listen(server)

//clients
var client = io.of('/');
 
 //listen for anyone connecting to default namespace
client.on('connection', function(client){
  
  
  client.upgradeTimeout = 300; // throwout time by inactivity
  
  clients.push(client); 
  //if new connection is made to server!
  console.log('have new client with id: ' + client.id);
  
  //define my listeners
  client.on("send_data", function(data) {
    
      console.log("emit data to other users: " + data);
      client.broadcast.emit("broadcast_data", data);

  });
  
  
  //listen for this client to disconnect
  client.on('disconnect', function(){
    
     clients.splice(clients.indexOf(client), 1);
     console.log('disconnected client: ' + client.id);

    
  });
  
  
  list_active_clients();
  var inout;
  client.broadcast.emit("allusers", {clientids, inout}); 
  
});


function list_active_clients(){
  
  clientids = [];
  
  for(let i=0;i<clients.length;i++){
    
    clientids.push(clients[i].id);
    
  }
 
}