Cara menggunakan php websocket client wss

Pada artikel ini kita akan belajar bagaimana cara mengimplementasikan websocket dengan menggunakan NodeJS.

WebSockets adalah alternatif komunikasi HTTP di Aplikasi Web. Teknologi ini menawarkan saluran komunikasi dua arah yang memiliki durasi yang panjang antara client dan server.

Kelebihan dari Websocket ini adalah menawarkan koneksi yang sangat cepat dengan latensi dan overhead yang rendah.

Perbedaan Websocket dengan HTTP

HTTP adalah protokol yang sangat berbeda, dan juga cara berkomunikasi yang berbeda. HTTP adalah protokol request/response dimana server akan mengembalikan data ketika client melakukan request.

Sedangkan pada WebSocket, server dapat mengirimkan request ke client tanpa klien secara eksplisit meminta request. Dalam hal ini client dan server dapat berkomunikasi satu sama lain secara bersamaan.

WebSocket sangat cocok untuk komunikasi real-time dengan durasi yang panjang sedangkan HTTP lebih cocok untuk pertukaran data satu arah yang diinisiasi oleh client.

Buat koneksi WebSocket baru

const url = 'wss://serversaya.com/alamat-websocket'
const connection = new WebSocket(url)

connectionadalah objek WebSocket. Ketika koneksi berhasil dibuat, maka script akan menjalanan sebuah event.

Ketika koneksi websocket berhasil di buka maka kita akan membuat sebuah function untuk menjalanan sebuah task pada properti onopen :

connection.onopen = () => {
  //...
}

Selanjutnya kita membuat sebuah function sebagai return jika terjadi kesalahan / error saat mengaktifkan koneksi websocket dengan properti onerror :

connection.onerror = error => {
  console.log(`WebSocket error: ${error}`)
}

Mengirim data ke server menggunakan WebSocket

Setelah koneksi terbuka, Anda dapat mengirim data ke server melalui websocket dengan NodeJS. Anda dapat melakukannya dengan menambahkan kode di dalam function onopen :

connection.onopen = () => {
  connection.send('halo')
}

Menerima data dari server menggunakan WebSocket

Untuk menerima data dari server, kita bisa menggunakan event onmessage :

connection.onmessage = e => {
  console.log(e.data)
}

Membuat server WebSocket dengan NodeJS

ws adalah library WebSocket yang populer untuk NodeJS. Kita akan menggunakan library tersebut untuk membangun server WebSocket.

Proses instalasi ws sangatlah mudah, Anda hanya perlu menalankan perintah berikut di console / terminal :

yarn init
yarn add ws

Setelah kita menginstall ws, kita dapat mulai mengimplementasikan Websocket dengan NodeJS untuk sisi server.

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received message => ${message}`)
  })
  ws.send('ho!')
})

Kode ini akan membuat server baru pada port 8080 (port default untuk WebSocket), dan menambahkan fungsi return saat koneksi dibuat, mengirim “halo juga!” ke client, dan menampilkan pesan dari client.

Penutup

Pada artikel ini kita sudah belajar bagaimana cara mengimplementasikan websocket dengan menggunakan NodeJS baik untuk sisi client maupun sisi server. Semoga bermanfaat

Jangan lupa kunjungi Ruang Koding untuk update terbaru lainnya.

  • Cara menggunakan php websocket client wss
    khashabawy
    Junior Member
  • Cara menggunakan php websocket client wss

  • Cara menggunakan php websocket client wss
    Cara menggunakan php websocket client wss

  • Posts: 24
    Threads: 15
    Joined: Oct 2014

    Reputation: 0


Hello guys ,

i want to build a web socket (ex : socket.io) application for a real time data ( chat with group of people )

how could this be accomplished using codeigniter  ?


It's important to realize that HTTP requests are accomplished by making a socket connection. The basic idea is that a client (e.g., a web browser) opens a socket connection, usually on port 80 (usually port 443 for HTTPS), to a web server and then uses that socket connection to request data from the web server using the HTTP protocol. E.g., it might send a request "GET /path/to/file.html" over the socket and the web server would respond by coughing up the html document. Depending on server and client configuration and the connection details, the client may request more files like images, CSS, and JS files before closing the socket connection.

Now if you are clever, you'll realize that by the time CodeIgniter comes into this scenario, the connection has already been made by the client to the web server and the web server runs your codeigniter code in response to the request. Basically, the socket connection has already been made and its waiting for a response from CodeIgniter over the open connection.

Within CodeIgniter, you might be able to create a new socket using socket_create_listen but this socket will only last as long as your CodeIgniter script is running. Once your script ends, the socket it created is likely to be closed and cleaned up during the garbage collection process-- unless you find a way to fork off a separate process form your code igniter script. You probably wouldn't want to fork off a process from your CodeIgniter system that opens a listening socket in response to many visitors coming. You might want to do this for a script accessible to administrators only. This sort of action is similar to rebooting a mail server or web server or firing up some kind of persistent service.

Another possibility is that your server might try to open a socket connection to someone else. A client might connect and say "hey my ip is 12.34.56.78 I want you to connect on port 1234" and then your server could use socket_connect to try and connect to the client but this in practice won't really work all that often because most users will be behind a firewall or a wireless router or something which is not set up to accept incoming socket connections on arbitrary ports. It takes a bit of know-how to set up NAT on one's LAN and you typically need a fairly capable router.

CodeIgniter *could* be used as a way to start/restart/reload/halt some kind of socket server on your web server, and CodeIgniter *might* be used in the construction of a socket server, but it seems quite awkward to me. I wrote a socket server in PHP called FlashMOG some time ago but haven't updated it in years.

  • Cara menggunakan php websocket client wss
    sachin205
    Newbie
  • Cara menggunakan php websocket client wss

  • Cara menggunakan php websocket client wss

  • Posts: 1
    Threads: 0
    Joined: Jan 2015

    Reputation: 0

  • Cara menggunakan php websocket client wss
    enajennairam
    Newbie
  • Cara menggunakan php websocket client wss

  • Cara menggunakan php websocket client wss

  • Posts: 2
    Threads: 0
    Joined: Apr 2015

    Reputation: 0


(01-19-2015, 11:57 PM)sachin205 Wrote:
(12-24-2014, 03:54 AM)Rufnex Wrote: Codeigniter cant do this out of the box. You can include a library like http://socketo.me/ that can do this or take a look at this projects

https://github.com/ranchor/socket-node-m...ter-chat-1
https://github.com/llbbl/codeigniter-chat


Hi Rufnex,
I am using ur thread "https://github.com/ranchor/socket-node-mysql-codeigniter-chat-1" for chatting in codeigniter. And it's perfectly working with mysql but i want to integrate it with POSTGRES. So please help me to integrate it with POSTGRES.
Thanks.

Just change your database configuration to postgre

db['default']['dbdriver'] = 'postgre';

And create the needed tables.


Handling realtime events properly is very hard and there is a lot of things to think about.

Quote:Vital for any production deployment, should be considered when choosing a real-time web technology including:
  • Vertical scalability (and performance in general)
  • Horizontal scalability via fault-tolerant clustering
  • Guaranteed delivery of data in presence of failures (e.g. if the connection between a client and a messaging server is broken or if the messaging server serving the client goes down, the client will reconnect to another cluster member and will receive all messages published during the reconnection time)
  • Security of data including data entitlement

Source: http://www.leggetter.co.uk/2013/12/09/ch...stack.html

Most of the stuff in above quote applies for large scale project and services, but anything can grow and you might end up with issues pointed out above.

This website is a good resource for information, what to think about and available services and libraries out there.

I always recommend these days to use services that can take care of all the "issues" for you, so that you can spend all your time on building a better experience and website for your users.

I personally have experience with Pusher Realtime service. It starts as free and goes up to enterprise level. It works nicely with CodeIgniter as well and I have created a library that anyone are welcome to use for any project.

  • Cara menggunakan php websocket client wss
    kishor10d
    Newbie
  • Cara menggunakan php websocket client wss

  • Cara menggunakan php websocket client wss

  • Posts: 3
    Threads: 0
    Joined: Aug 2016

    Reputation: 0

  • Cara menggunakan php websocket client wss
    shihasck
    Newbie
  • Cara menggunakan php websocket client wss

  • Cara menggunakan php websocket client wss

  • Posts: 8
    Threads: 5
    Joined: May 2016

    Reputation: 0

  • Cara menggunakan php websocket client wss
    dpentavia
    Newbie
  • Cara menggunakan php websocket client wss

  • Cara menggunakan php websocket client wss

  • Posts: 1
    Threads: 0
    Joined: Jul 2017

    Reputation: 0


(09-18-2016, 11:50 PM)kishor10d Wrote: Hello everyone,
Here I try to create a websocket (PHP Ratchet) application integrated with CodeIgniter.
Please take a look, I think you find it useful.

https://github.com/kishor10d/CodeIgniter...-Websocket

Please visit the link and download the repository.

is this working without angular?