after connect with start_link the client start sending infinite messages
Closed this issue · 1 comments
Hi, for me it's not clear how correct use websockex, I did an small websocket server which when receive a message reply with "hello you sent -> your_message", basically I need send a message and get the response
import * as express from 'express';
import * as http from "http";
import * as WebSocket from 'ws';
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({server});
wss.on('connection', (ws: WebSocket) => {
ws.send("hi I'm ready");
ws.on('message', (message: string) => {
console.log(`received ${message}`);
ws.send(`hello you sent -> ${message}`);
})
});
server.listen(8999,()=>{
//para correrlo se puede hacer con ts-node server.ts
console.log("server running on port 8999")
})
now I'm trying to connect to this server with websockex with this code
defmodule WebsocketCommunicator do
use WebSockex
require Logger
def start_link(opt \\ []) do
WebSockex.start_link("ws://localhost:8999",__MODULE__,:fake_state,opt)
end
def handle_connect(_conn, state) do
Logger.info("Connected!")
{:ok, state}
end
def echo(client,message) do
Logger.info("mandando mensaje #{message}")
WebSockex.send_frame(client, {:text, message})
end
def handle_frame({:text,msg},:fake_state) do
Logger.info("sending --> #{msg}")
{:reply,{:text,msg},:fake_state}
end
end
but when I try to run this
{:ok,pid} = WebsocketCommunicator.start_link()
I get
sending --> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent -> hello you sent
how can send and get the websocket response with websockex???...why after connect with start_link start sending messages?...
sorry for my noobs questions, thank you so much
wss.on('connection', (ws: WebSocket) => {
ws.send("hi I'm ready"); // <--- This Line
ws.on('message', (message: string) => {
console.log(`received ${message}`);
ws.send(`hello you sent -> ${message}`);
})
});
As soon as you're connected you're sending a message. Then you have a weird loop where each side is handling the text message by replying with the message. they just recieved.
ws.send(`hello you sent -> ${message}`);
{:reply,{:text,msg},:fake_state}
Just make it so that one side doesn't reply with the message that was sent.