websocket练习
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练习的更多相关文章
- 漫扯:从polling到Websocket
Http被设计成了一个单向的通信的协议,即客户端发起一个request,然后服务器回应一个response.这让服务器很为恼火:我特么才是老大,我居然不能给小弟发消息... 轮询 老大发火了,小弟们自 ...
- 细说WebSocket - Node篇
在上一篇提高到了 web 通信的各种方式,包括 轮询.长连接 以及各种 HTML5 中提到的手段.本文将详细描述 WebSocket协议 在 web通讯 中的实现. 一.WebSocket 协议 1. ...
- java使用websocket,并且获取HttpSession,源码分析
转载请在页首注明作者与出处 http://www.cnblogs.com/zhuxiaojie/p/6238826.html 一:本文使用范围 此文不仅仅局限于spring boot,普通的sprin ...
- WebSocket - ( 一.概述 )
说到 WebSocket,不得不提 HTML5,作为近年来Web技术领域最大的改进与变化,包含CSS3.离线与存储.多媒体.连接性( Connectivity )等一系列领域,而即将介绍的 WebSo ...
- php+websocket搭建简易聊天室实践
1.前言 公司游戏里面有个简单的聊天室,了解了之后才知道是node+websocket做的,想想php也来做个简单的聊天室.于是搜集各种资料看文档.找实例自己也写了个简单的聊天室. http连接分为短 ...
- Demo源码放送:打通B/S与C/S !让HTML5 WebSocket与.NET Socket公用同一个服务端!
随着HTML5 WebSocket技术的日益成熟与普及,我们可以借助WebSocket来更加方便地打通BS与CS -- 因为B/S中的WebSocket可以直接连接到C/S的服务端,并进行双向通信.如 ...
- Cowboy 开源 WebSocket 网络库
Cowboy.WebSockets 是一个托管在 GitHub 上的基于 .NET/C# 实现的开源 WebSocket 网络库,其完整的实现了 RFC 6455 (The WebSocket Pro ...
- 借助Nodejs探究WebSocket
文章导读: 一.概述-what's WebSocket? 二.运行在浏览器中的WebSocket客户端+使用ws模块搭建的简单服务器 三.Node中的WebSocket 四.socket.io 五.扩 ...
- 细说websocket - php篇
下面我画了一个图演示 client 和 server 之间建立 websocket 连接时握手部分,这个部分在 node 中可以十分轻松的完成,因为 node 提供的 net 模块已经对 socket ...
- webSocket and LKDBHelper的使用说明
socketket与lkdbhelper来处理数据 客户需求: 当我们有需要从自己的后台推送消息给我们的用户时,用户需要实时的接收到来自我们的推送消息.前提是没有使用第三方的推送框架,那么这个使用we ...
随机推荐
- SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession
可以说每个MyBatis都是以一个SqlSessionFactory实例为中心的.SqlSessionFactory实例可以通过SqlSessionFactoryBuilder来构建.一是可以通过XM ...
- 【Linux开发】linux设备驱动归纳总结(十一):写个简单的看门狗驱动
linux设备驱动归纳总结(十一):写个简单的看门狗驱动 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ...
- WinForm笔记1:TextBox编辑时和DataGridView 单元格编辑时 的事件及其顺序
TextBox 编辑框 When you change the focus by using the mouse or by calling the Focus method, focus event ...
- Durable NAND flash memory management
词条积累 1.NAND flash memory http://www.searchstorage.com.cn/whatis/word_6052.htm http://baike.baidu.com ...
- 【监控实践】【4.4】使用DMV和函数监控数据库状态和资源使用
1.查看当前实例运行进程 -- 核心DMV.函数.系统SP:/* 所有进程请求:sys.dm_exec_requests 所有进程与连接:sys.sysprocesses 系统函数,查看sql:sys ...
- 【B2B】01-BFS
纠正我对 01-BFS 问题的错误认识. 我一直以为对于 01-BFS,每次点 $u$ 出队时,对于 $u$ 的邻接边表中的边,只要先松弛边权为 0 的边再松弛边权为 1 的边就能保证每个点只入队一次 ...
- 【面试向】2019 年微软秋招笔试 Problem 3
Problem Check if a positive integer $n$ can be written as sum of a positive integer and reverse of t ...
- [LGP2000] 拯救世界
6的倍数 1/(1-x^6) 最多9块 (1-x^10)/(1-x) 最多5块 (1-x^6)/(1-x) 4的倍数 1/(1-x^4) 最多7块 (1-x^8)/(1-x) 2的倍数 1/(1-x^ ...
- Swoft 2.0.5 更新,新增高效秒级定时任务、异常管理组件
什么是 Swoft ? Swoft 是一款基于 Swoole 扩展实现的 PHP 微服务协程框架.Swoft 能像 Go 一样,内置协程网络服务器及常用的协程客户端且常驻内存,不依赖传统的 PHP-F ...
- MySQL创表--分页--自关联--
创建表book create table t_book( id int unsigned auto_increment primary key, bookName varchar(255) defau ...