在C#源码中使用WebSocket服务发送消息
niunan:
又搜索到另一篇博客,用下面的代码就可以了。。。
[code=plain]
public class TestController : Controller
{
public ActionResult SendMessageToWebSocket()
{
string url = "ws://localhost:23338/api/chat";
//nuget 搜索 WebSocketSharp-netstandard
//WebSocketSharp.WebSocket websocket = new WebSocketSharp.WebSocket(url, new String[] { "any" });
//websocket.Connect();
//websocket.Send("this is a test -- "+DateTime.Now); //报错: The current state of the connection is not Open
//websocket.Close();
try
{
System.Net.WebSockets.ClientWebSocket cln = new System.Net.WebSockets.ClientWebSocket();
cln.ConnectAsync(new Uri(url), new CancellationToken()).Wait();
cln.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes("my message")), System.Net.WebSockets.WebSocketMessageType.Text, true, new CancellationToken()).Wait();
}
catch (Exception
|