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

websocket练习的更多相关文章

  1. 漫扯:从polling到Websocket

    Http被设计成了一个单向的通信的协议,即客户端发起一个request,然后服务器回应一个response.这让服务器很为恼火:我特么才是老大,我居然不能给小弟发消息... 轮询 老大发火了,小弟们自 ...

  2. 细说WebSocket - Node篇

    在上一篇提高到了 web 通信的各种方式,包括 轮询.长连接 以及各种 HTML5 中提到的手段.本文将详细描述 WebSocket协议 在 web通讯 中的实现. 一.WebSocket 协议 1. ...

  3. java使用websocket,并且获取HttpSession,源码分析

    转载请在页首注明作者与出处 http://www.cnblogs.com/zhuxiaojie/p/6238826.html 一:本文使用范围 此文不仅仅局限于spring boot,普通的sprin ...

  4. WebSocket - ( 一.概述 )

    说到 WebSocket,不得不提 HTML5,作为近年来Web技术领域最大的改进与变化,包含CSS3.离线与存储.多媒体.连接性( Connectivity )等一系列领域,而即将介绍的 WebSo ...

  5. php+websocket搭建简易聊天室实践

    1.前言 公司游戏里面有个简单的聊天室,了解了之后才知道是node+websocket做的,想想php也来做个简单的聊天室.于是搜集各种资料看文档.找实例自己也写了个简单的聊天室. http连接分为短 ...

  6. Demo源码放送:打通B/S与C/S !让HTML5 WebSocket与.NET Socket公用同一个服务端!

    随着HTML5 WebSocket技术的日益成熟与普及,我们可以借助WebSocket来更加方便地打通BS与CS -- 因为B/S中的WebSocket可以直接连接到C/S的服务端,并进行双向通信.如 ...

  7. Cowboy 开源 WebSocket 网络库

    Cowboy.WebSockets 是一个托管在 GitHub 上的基于 .NET/C# 实现的开源 WebSocket 网络库,其完整的实现了 RFC 6455 (The WebSocket Pro ...

  8. 借助Nodejs探究WebSocket

    文章导读: 一.概述-what's WebSocket? 二.运行在浏览器中的WebSocket客户端+使用ws模块搭建的简单服务器 三.Node中的WebSocket 四.socket.io 五.扩 ...

  9. 细说websocket - php篇

    下面我画了一个图演示 client 和 server 之间建立 websocket 连接时握手部分,这个部分在 node 中可以十分轻松的完成,因为 node 提供的 net 模块已经对 socket ...

  10. webSocket and LKDBHelper的使用说明

    socketket与lkdbhelper来处理数据 客户需求: 当我们有需要从自己的后台推送消息给我们的用户时,用户需要实时的接收到来自我们的推送消息.前提是没有使用第三方的推送框架,那么这个使用we ...

随机推荐

  1. IDEA 控制台中文乱码的问题

    -Dfile.encoding=UTF-8

  2. NOIp2017D1T2 时间复杂度【模拟】

    说一说 题目分析请从目录空降... 没想到模拟题还会卡这么久...菜得真实... 这是一个励志的故事:从$0pts->9pts->18pts->27pts->36tps-> ...

  3. 【CUDA开发】Cuda C++ Thrust API与 Cuda Runtime API程序比较

    今天买了本新书<高性能CUDA应用设计与开发方法与最佳实践>,今天读了第一章有点出获,分享给大家. 程序功能:给向量填充数据并计算各元素之和 1. CPU串行运行的代码: //seqSer ...

  4. PHP 调用shell命令

    可以使用的命令: popenfpassthrushell_execexecsystem 1.popen resource popen ( string command, string mode ) 打 ...

  5. gzip 命令

    NAME gzip -- compression/decompression tool using Lempel-Ziv coding (LZ77) SYNOPSIS gzip [-cdfhkLlNn ...

  6. PTA(Basic Level)1023.组个最小数

    给定数字 0-9 各若干个.你可以以任意顺序排列这些数字,但必须全部使用.目标是使得最后得到的数尽可能小(注意 0 不能做首位).例如:给定两个 0,两个 1,三个 5,一个 8,我们得到的最小的数就 ...

  7. Spread.NET 表格控件 V12.0 Update2 发布更新

    Spread.NET表格控件V12.0 Update 2 已经正式发布,本次发布主要针对WinForm平台下客户反馈的产品使用功能进行优化,并修复了已知问题,具体修复情况见下方说明. Spread.N ...

  8. Fiddle-常用设置和操作记录

    1.导出证书: 2.清空屏幕: 3.字段认识 4.保存会话: 5.解码

  9. Python使用pycharm导入pymysql

    file->setting->project->project interperter,双击右侧出现的pip,弹出安装包,搜索pymysql->选择第一个->Instal ...

  10. [转载]for、foreach、iterator的用法及效率区别

    来源:https://www.jianshu.com/p/bbb220824c9a 1.在形式上 for的形式是 for(int i=0;i<arr.size();i++){...} forea ...