sta / websocket-sharp

A C# implementation of the WebSocket protocol client and server
http://sta.github.io/websocket-sharp
MIT License
5.72k stars 1.66k forks source link

Receive message issue #287

Open tarim opened 8 years ago

tarim commented 8 years ago

Hi There,

I am trying to use websocket-sharp on my application, and I have an issue receive messages. Can anyone help me please?

Here is my code: var receiveData=string.Empty(); var webSocket = new WebSocket(url); webSocket.OnOpen += (sender, e) => { }; webSocket.OnMessage += (sender, e) => { }; webSocket.Connect(); webSocket.Send(message); webSocket.OnMessage += (sender, e) => { if (e.IsText && !e.IsPing) { receiveData = e.Data; } }; Console.WriteLine(receiveData); // receiveData always empty webSocket.Close();

GibbOne commented 8 years ago

I guess that you close the socket too early. Try to add a simple Console.ReadLine just before Console.WriteLine(receiveData);

tarim commented 8 years ago

Hi @GibbOne,

Thank you very much for your response. I tried, but it still doesn't work. Also, real application normally we don't do console write or read, so we don't have console read at all. So, I don't know why receiveData doesn't have value. Any suggestion please?

Thank you,

NS

michaelekaufman commented 8 years ago

You have 2 OnMessage event handlers and the second event handler is setup after the Connect call so I can only assume the second handler, which has code, never triggers. Try this..

var receiveData=string.Empty();
var webSocket = new WebSocket(url);
webSocket.OnOpen += (sender, e) => { };
webSocket.OnMessage += (sender, e) =>
{
if (e.IsText && !e.IsPing)
{
receiveData = e.Data;
}
};
webSocket.Connect();
webSocket.Send(message);

Console.WriteLine(receiveData); // receiveData always empty
webSocket.Close();