Ubuntu Sunucuya Socket io Kurulumu

Websocket kullanmak istiyorsunuz o zaman adım adım ubuntu sunucunuzu konfigüre edelim

ilk olarak aşağıdaki komutları kullarak ilgili kurulumları yapalım

sudo su
apt update
apt upgrade -y
apt install nginx -y 
nano /etc/nginx/sites-available/default
# paste the nginx configuration
#check syntax is ok
nginx -t
service nginx restart
curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
bash nodesource_setup.sh
apt install nodejs -y
apt install build-essential
npm install pm2@latest -g
cd /var/www/html
mkdir chatapp
cd chatapp
npm init
npm install -s express
npm install -s body-parser
npm install -s socket.io
npm install -s http
#create index.html and paste the index.html code
nano index.html
#create index.js and paste the index.js code
nano index.js
pm2 start index.js
pm2 startup systemd
pm2 save
systemctl start pm2-root

Şimdi geldim index.js (server kurulumu)

var express = require('express');
var bodyParser = require('body-parser')
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))

app.get('/messages', (req, res) => {
  res.send("ffsd");
})

app.post('/messages', (req, res) => {
	console.log(req.body);
  io.emit('message', req.body);
  res.sendStatus(200);
})

io.on('connection', () =>{
  console.log('a user is connected')
})

var server = http.listen(3000, () => {
  console.log('server is running on port', server.address().port);
});

nginix ayarları

server {
    listen 80;
    server_name socket.hasanaylas.com;
    root /var/www/html/hasanaylas.com/websocket;
    index index.html index.htm index.nginx-debian.html;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    listen 443 ssl;
    server_name socket.hasanaylas.com;
    root /var/www/html/hasanaylas.com/websocket;
    index index.html index.htm index.nginx-debian.html;

    ssl_certificate /etc/letsencrypt/live/socket.hasanaylas.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/socket.hasanaylas.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;  # Güncel SSL protokollerini belirtin

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}


şimdi index.html kuralım
<!DOCTYPE html>
<html>
<head>
  <title>My First Node App</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
  <script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var port = location.port;
var url = window.location.href;
var domain = (new URL(url));
domain = domain.hostname+(port==80?"":":"+port);
</script>
<div class="container">
    <br>
    <div class="jumbotron">
        <h1 class="display-4">Send Message</h1>
        <br>
        <input id = "name" class="form-control" placeholder="Name">
        <br>
        <textarea id = "message" class="form-control" placeholder="Your Message Here"></textarea>
        <br>
        <button id="send" class="btn btn-success">Send</button>
    </div>
    <div id="messages">

    </div>
</div>
<script>
   var socket = io();
    $(() => {
        $("#send").click(()=>{
            sendMessage({name: $("#name").val(), message: $("#message").val()});
        })

        getMessages()
    })

    socket.on('message', addMessages)

    function addMessages(message){
        $("#messages").append(`<h4> ${message.name} </h4> <p> ${message.message} </p>`)
    }

    function getMessages(){
      $.get(`http://${domain}/messages`, (data) => {
        data.forEach(addMessages);
      })
    }

    function sendMessage(message){
      $.post(`http://${domain}/messages`, message)
    }
</script>
</body>
</html>

index.js oluşturup serveri ayağa kaldırdınız ama burada güvenlik önlemlerini almayı unutmayın index.js e dışarıdan izin vermeyin ulasmaya

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir