html代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>WebSocket DEMO</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
ul,
li {
padding: 0;
margin: 0;
list-style: none;
}
</style>
</head>
<body>
<div>
a:<input type="text" id="inpA" /> b:<input type="text" id="inpB" />
<button type="button" id="btnSub">submit</button>
</div>
<ul id="outCnt"></ul>
<script>
let wsc;
var echo = function(text) {
var echoone = function(text) {
var dom = document.createElement("li");
var t = document.createTextNode(text);
dom.appendChild(t);
var cnt = document.getElementById("outCnt");
cnt.appendChild(dom);
};
if (Array.isArray(text)) {
text.map(function(t) {
echoone(t);
});
} else {
echoone(text);
}
};
(function() {
if ("WebSocket" in window) {
// init the websocket client
wsc = new WebSocket("ws://localhost:6690/add");
wsc.onopen = function() {
echo("connected");
};
wsc.onclose = function() {
echo("closed");
};
wsc.onmessage = function(e) {
var data = JSON.parse(e.data);
echo(data.msg || e.data);
console.log(data.msg || e.data);
}; // define click event for submit button
document.getElementById("btnSub").addEventListener('click', function() {
var a = parseInt(document.getElementById("inpA").value);
var b = parseInt(document.getElementById("inpB").value);
if (wsc.readyState == 1) {
wsc.send(JSON.stringify({ a: a, b: b }));
} else {
echo("service is not available");
}
});
}
})();
</script>
</body>
</html>

服务端代码

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
using WebSocketSharp.Server; namespace ConsoleServer
{
public class Add : WebSocketBehavior
{ protected override void OnOpen()
{
Console.WriteLine("Connection Open");
base.OnOpen();
}
protected override void OnMessage(MessageEventArgs e)
{
var data = e.Data;
if (TestJson(data))
{
var param = JToken.Parse(data);
if (param["a"] != null && param["b"] != null)
{
var a = param["a"].ToObject<int>();
var b = param["b"].ToObject<int>();
Send(JsonConvert.SerializeObject(new { code = , msg = "result is " + (a + b) }));
Task.Factory.StartNew(() => {
Task.Delay().Wait();
Send(JsonConvert.SerializeObject(new { code = , msg = "I just to tell you, the connection is different from http, i still alive and could send message to you." }));
});
}
}
else
{
Send(JsonConvert.SerializeObject(new { code = , msg = "request is not a json string." }));
}
} protected override void OnClose(CloseEventArgs e)
{
Console.WriteLine("Connection Closed");
base.OnClose(e);
} protected override void OnError(ErrorEventArgs e)
{
Console.WriteLine("Error: " + e.Message);
base.OnError(e);
} private static bool TestJson(string json)
{
try
{
JToken.Parse(json);
return true;
}
catch (JsonReaderException ex)
{
Console.WriteLine(ex);
return false;
}
}
}
}

Program启动项代码

 var wssv = new WebSocketServer();
wssv.AddWebSocketService<Add>("/add");
wssv.Start();
Console.WriteLine("Server starting, press any key to terminate the server.");
Console.ReadKey(true);
wssv.Stop();

注意引用 Newtonsoft.JSON和DSharpPlus.WebSocket.WebSocketSharp

package代码

  Install-Package DSharpPlus.WebSocket.WebSocketSharp 

  Install-Package Newtonsoft.JSON

最新文章

  1. Android Fragment 解析和使用
  2. OC中的面向对象语法
  3. 如何使用 UC浏览器开发者版 进行移动端调试
  4. mysql常用脚本
  5. &#39;DEVENV&#39; is not recognized as an internal or external command,
  6. ORA-00937:不是单组分组函数_Oracle
  7. HDU4731+找规律
  8. 二、mongo数据库
  9. git命令之git mergetool vi非正常退出.swp删除不了的问题
  10. [Swift]LeetCode762. 二进制表示中质数个计算置位 | Prime Number of Set Bits in Binary Representation
  11. python3 文件操作
  12. IOS 生成静态库文件(.a文件)
  13. 14:CSS3 渐变(gradient)与 过度(transition)、CSS3 的2D动画
  14. [leetcode]86. Partition List划分链表
  15. java outterLoop跳出多重循环用法以及详解
  16. C++max的使用方法
  17. 跟未名学Office - PPT核心:表达
  18. Mysql 之闪回技术 binlog2sql
  19. day31 粘包问题
  20. Quartz(强大的定时器)

热门文章

  1. selenium-server--chromedriver环境
  2. spring笔记3路径跳转
  3. 【Bell-Ford 算法】CLRS Exercise 24.1-4,24.1-6
  4. HDU2087 剪花布条(字符串...半暴力写的?
  5. Git服务器搭建与配置管理
  6. Select2的远程数据操作
  7. FastDFS集群部署(转载 写的比较好)
  8. RBAC(基于角色的访问控制)用户权限管理数据库设计
  9. 用java语言(文件和文件流知识点)实现图片的拷贝,从d盘拷贝到e盘
  10. hive各种报错