NET WebSocket
2019年9月12日
WebSocket是什么我就不多说了,去百度百科,搜索一下,他会比我写的更全面,更细致
但是需要简单说两句,WebSocket分为,两端,一个是客户端,一个是服务端,客户端你也可以理解为页面,服务器端可以理解为后台,所以每次先启动服务端,在启动客户端,原理就不多说了,(先当孙子再当爷)
这几天需要socket,踩了不少坑,所以把代码直接拿出来,让大家看看,话说net socket这方面的代码挺少的,一搜索都是java的,(疯狂暗示微软,需要努力了)话不多说,直接上代码
范文一
需要引用程序包SuperWebSocket;和SuperSocket;和Newtonsoft.Json;
需要引用程序包SuperWebSocket;和SuperSocket;和Newtonsoft.Json;
需要引用程序包SuperWebSocket;和SuperSocket;和Newtonsoft.Json;
重要的事情说三遍
代码添加到程序后,需要第三方应用(Postman),开启《http://localhost:50186/TestWebSocket/Start》接口
或者浏览器直接访问开启《http://localhost:50186/TestWebSocket/Start》接口
http://localhost:50186/是我的地址,你需要找到你自己的地址
这是页面代码 HTML5
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<input type="text" id="txtName" />
<input type="button" value="加入聊天室" id="btnConnection" />
<input type="button" value="离开聊天室" id="btnDisConnection" />
<input type="text" id="txtInput" />
<input type="button" value="发送" id="btnSend" />
<div id="msg"></div>
<script language="javascript" type="text/javascript">
var ws;
var url = "ws://192.168.61.1:1010"
$("#btnConnection").click(function () {
if ("WebSocket" in window) {
ws = new WebSocket(url);
}
else if ("MozWebSocket" in window) {
ws = new MozWebSocket(url);
}
else
alert("浏览器版本过低,请升级您的浏览器");
//注册各类回调
ws.onopen = function () {
$("#msg").append($("#txtName").val() + "加入聊天室<br />");
}
ws.onclose = function () {
$("#msg").append($("#txtName").val() + "离开聊天室<br />");
}
ws.onerror = function () {
$("#msg").append("数据传输发生错误<br />");
}
ws.onmessage = function (receiveMsg) {
$("#msg").append(receiveMsg.data + "<br />");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
ws.close();
}
});
//$("#btnDisConnection").click(function () {
// $("#msg").append($("#txtName").val() + "离开聊天室<br />");
// ws.close();
//});
$("#btnSend").click(function () {
if (ws.readyState == WebSocket.OPEN) {
var message = "{\"name\":\"" + $("#txtName").val() + "\",\"message\":\"" + $("#txtInput").val() + "\"}";
ws.send(message);
}
else {
$("#msg").text("Connection is Closed!");
}
});
</script>
控制器
using Newtonsoft.Json;
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebSocket.Controllers
{
public class TestWebSocketController : Controller
{
WebSocketServer server;
List<SessionInfo> listSession = new List<SessionInfo>();
public ActionResult Index()
{
return View();
}
//服务启动
public string Start()
{
var ip = "192.168.61.1";//这里是地址,我的是局域网,你要是不知道怎么获取ip地址,那你就win+r输入cmd回车,在输入ipconfig在进行回车,那个ipv4就是ip地址
var port = "1010";//这是一个端口,找个空闲的端口填写上去,就万事大吉了
server = new WebSocketServer();
if (!server.Setup(ip, int.Parse(port)))
{
return "WebSocket服务启动出现错误";
}
//新的会话连接
server.NewSessionConnected += SessionConnected;
//会话关闭
server.SessionClosed += SessionClosed;
//新的消息接收
server.NewMessageReceived += MessageReceived;
if (!server.Start())
{
//处理监听失败消息
return "error";
}
return "success";
}
/// <summary>
/// 会话关闭
/// </summary>
/// <param name="session"></param>
/// <param name="value"></param>
private void SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
Debug.WriteLine("会话关闭,关闭原因:{0} 来自:{1} 时间:{2:HH:MM:ss}", value, session.RemoteEndPoint, DateTime.Now);
//SendMsgToRemotePoint(SessionId, SessionId + "已断开");
var sessionRemove = listSession.FirstOrDefault(s => s.SessionId == session.SessionID);
listSession.Remove(sessionRemove);
}
/// <summary>
/// 会话连接
/// </summary>
/// <param name="session"></param>
private void SessionConnected(WebSocketSession session)
{
Debug.WriteLine("新的会话连接 来自:{0} SessionID:{1} 时间:{2:HH:MM:ss}", session.RemoteEndPoint, session.SessionID, DateTime.Now);
listSession.Add(new SessionInfo { SessionId = session.SessionID, EndPoint = session.RemoteEndPoint.ToString() });
}
/// <summary>
/// 消息接收
/// </summary>
/// <param name="session"></param>
/// <param name="value"></param>
private void MessageReceived(WebSocketSession session, string value)
{
//反序列化消息内容
var message = JsonConvert.DeserializeObject<MessageInfo>(value);
foreach (var item in listSession)
{
///发送消息
SendMsg(item.SessionId, string.Format("{0}发来消息:{1}", message.Name, message.Message));
}
}
// <summary>
/// 发送消息
/// </summary>
/// <param name="sessionId"></param>
/// <param name="msg"></param>
private void SendMsg(string sessionId, string msg)
{
var appSession = server.GetAppSessionByID(sessionId);
if (appSession != null)
appSession.Send(msg);
}
public class MessageInfo
{
public string Name { get; set; }
public string Message { get; set; }
}
public class SessionInfo
{
public string SessionId { get; set; }
public string EndPoint { get; set; }
//public string Name { get; set; }
}
}
}
范文二
页面需要引用一个jquery.cookie.js
外加一个一个jquery.js,这个一般都在scipts文件里里都有
这个时候你又要问这个js哪里下载?
下载地址
看到一个Download now点击就可以了
如果找不到 那就Ctrl+F 搜索一下
说完客户端了,那我们再来聊一聊服务端,服务端是用的控制台应用程序书写的
需要引用Fleck程序包
这是页面代码 HTML5
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.cookie.js"></script>
<script>
$(document).ready(function () {
$.cookie('userID', '0000');
var wsImpl = window.WebSocket || window.MozWebSocket;
var data = $("#Data");
data.append("连接到服务器..........<br/>");
// 创建新的websocket新连接端口为7181
window.ws = new wsImpl('ws://192.168.61.1:8885?id=' +'039ee21d340d4-2c3ec9d0-d2f2-4061-8df1-6d8b51e3c9c2');
// 当数据从服务器服务中心发送后,继续向下运行过程
ws.onmessage = function (evt) {
data.append(evt.data + '<br/>');
};
// 当链接对象找到服务端成功对接后,提示正常打开
ws.onopen = function () {
data.append('连接成功<br/>' );
};
// 当链接对象未找找到服务端成功对接后,提示打开失败,别切单项关闭
ws.onclose = function () {
data.append('连接失败<br/>');
}
$("#Submit").click(function () {
var text = $("#Text").val();
ws.send(text);
$("#Text").val("");
})
})
</script>
</head>
<body>
<div>
输入内容<input type="text" id="Text" /><input type="button" id="Submit" value="提交" />
</div>
<div>
<pre id="Data"></pre>
</div>
</body>
</html>
服务端是用的控制台应用程序书写的,不要放错地方了
using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
FleckLog.Level = LogLevel.Debug;
var allSockets = new List<IWebSocketConnection>();
var server = new WebSocketServer("ws://192.168.61.1:8885");
server.Start(socket =>
{
socket.OnOpen = () => //当建立Socket链接时执行此方法
{
var data = socket.ConnectionInfo; //通过data可以获得这个链接传递过来的Cookie信息,用来区分各个链接和用户之间的关系(如果需要后台主动推送信息到某个客户的时候,可以使用Cookie)
var UID = data.Path;///?id=039ee21d340d4-2c3ec9d0-d2f2-4061-8df1-6d8b51e3c9c2
allSockets.Add(socket);
};
socket.OnClose = () =>// 当关闭Socket链接十执行此方法
{
Console.WriteLine("客户端关闭!");
allSockets.Remove(socket);
};
socket.OnMessage = message =>// 接收客户端发送过来的信息
{
Console.WriteLine(message);
socket.Send("客户端: " + message);
//allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
};
});
var input = Console.ReadLine();
while (input != "exit")
{
//q.socket
foreach (var socket in allSockets.ToList())
{
socket.Send(input);
}
input = Console.ReadLine();
}
}
}
}
这两篇范文都是别人写的,但是非常好用,链接地址找不到了,如果原作者有幸看到请加我好友,我们商量一下解决办法
或者这里不方便请加我qq好友 22264523916 我们来聊