NetCoreServer
NetCoreServer copied to clipboard
One Client
Hello dear how to send one message to a specific client ?
Hi @arsium ,
please find the below example code. like that you can send a message to specific client.
TcpSession session = Server.FindSession(new Guid("<id of that particular client>"));
Console.WriteLine($"session value {session}");
session?.SendAsync($"Message text here");
note: here server denotes object of the TcpServer by NetCoreServer
Thx !
Hello @chronoxor , but how do you know the original client Guid?. Perhaps is necessary in OnConnected() return the Guid that was assign to the client and in the main app store in a dictionary and unique identifier for the client (it maybe the ipdaddress:port) and in the value the Guid for that client
Each session and client has unique Id property with Guid type. You can access to all connected sessions in server using Sessions property or handle them in your own server implementation overriding OnConnected(TcpSession session)
handler.
Thought I would add.... if you're adding statements to the OnWsReceived
function (or surrounding statements) you can simply type SendTextAsync("yourMessageHere")
and it will send a reply to the client whose session is established in this context.
Example:
public override void OnWsReceived(byte[] buffer, long offset, long size)
{
string message = Encoding.UTF8.GetString(buffer, (int)offset, (int)size);
Console.WriteLine("Incoming: " + message);
SendTextAsync($"You sent {message}");
// If the buffer starts with '!' the disconnect the current session
if (message == "!")
Close(1000);
}
Would reply with the message sent.
Correct me if I'm wrong guys? 😊
Hello,
@Mohamed-Abubucker I used your code to try to send a message to a session, but for some reason the client is not receiving the message.
I tried Send and SendAsync
Any ideas?
For WebSockets protocol you need to call SendText()/SendTextAsync()/SendBinary()/SendBinaryAsync() methods
For some reason I only have these methods...
Try (ChatSession)session
Perfect! Thank you very much.
Final working code to send a message to a specific session:
// Send to specific session
ChatSession session = (ChatSession)server.FindSession(new Guid(sessionID));
Console.WriteLine($"sending to session ID {sessionID} message {message}");
session?.SendTextAsync(message);