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 ...
随机推荐
- webgoat8百度云下载链接
网络不好的很难下载,网上也没什么好用的下载链接,我就上传了百度网盘,有需要的兄弟自己下. 链接:https://pan.baidu.com/s/1plTxkZUhSZm9vA5GGzYmMQ 提取码: ...
- php 二维数据排序 排行榜
php 二维数据排序 排行榜 $rateCount = array(); foreach($groupUsers as $user){ $rateCount[] = $user['rate']; } ...
- 题目---汉诺塔及AI代码及八皇后
2019春第十一周作业 这个作业属于那个课程 C语言程序设计II 这个作业要求在哪里 https://edu.cnblogs.com/campus/zswxy/software-engineering ...
- Largest Number At Least Twice of Others
In a given integer array nums, there is always exactly one largest element. Find whether the largest ...
- Postman之获得登录的token,并设置为全局变量
1.调通登录接口(可以参考上篇博客) 网址:Postman之简单使用 2.粘贴以下代码到Tests中 //把json字符串转化为对象 var data=JSON.parse(responseBody) ...
- mysql添加索引造成的影响
尽管添加索引可以优化SQL语句的性能,但是添加索引的同时也会带来不小的开销.尤其是在有大量的索引的情况下. mysql添加索引造成的影响如下: 1.DML(数据操作语言)影响,在表上添加缩影会直接影响 ...
- spring boot 发布自动生成svn版本号
通过Jenkins构建发布spring boot项目时,常常有需求,需要把Svn的版本号更新到项目的版本上,通过有两种解决方案: 1. 通过shell命令对配置文件中的指定字符进行替换, 如: 配置文 ...
- 爆路径写后门拿shell的一些姿势
[PhpMyAdmin后台拿Shell]CREATE TABLE `mysql`.`xiaoma` (`xiaoma1` TEXT NOT NULL );INSERT INTO `mysql`.`xi ...
- 在iPhone开发中实现解压缩gzip
在iPhone开发中实现解压缩gzip是本文要介绍的内容,最近做的一个东西中,需要从网络获取xml文件,但是该文件用了gzip压缩的.搜索一 下有人说gzip压缩的用urlrequest可以自己解压, ...
- ab测试工具的使用
下载地址:http://httpd.apache.org/download.cgi#apache24 编译安装后在安装目录bin下可以找到ab执行程序 基本用法: ab -n 5000 -c 1000 ...