好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

WebSocket协议应用实例的JAVASCRIPT+C#在.Net framework4.8框架下

WebSocket协议应用实例的JAVASCRIPT+C#在.Net framework4.8框架下使用的源码

以下是基于.NET Framework 4.8与JavaScript的WebSocket全双工通信实现方案,包含服务端(C#)和客户端(JavaScript)完整代码:

一、C#服务端实现(.NET Framework 4.8)

// 需引用System.Net.WebSockets和Newtonsoft.Json

using System;

using System.Net;

using System.Net.WebSockets;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

public class WebSocketServer

{

    private readonly HttpListener _listener = new HttpListener();

    private readonly CancellationTokenSource _cts = new CancellationTokenSource();

    public async Task StartAsync(string url)

    {

        _listener.Prefixes.Add(url);

        _listener.Start();

        Console.WriteLine($"服务端已启动,监听 {url}");

        while (!_cts.IsCancellationRequested)

        {

            var context = await _listener.GetContextAsync();

            if (context.Request.IsWebSocketRequest)

            {

                ProcessWebSocketRequest(context);

            }

            else

            {

                context.Response.StatusCode = 400;

                context.Response.Close();

            }

        }

    }

    private async void ProcessWebSocketRequest(HttpListenerContext context)

    {

        var ws = await context.AcceptWebSocketAsync(null);

        var buffer = new byte[1024];

        while (ws.WebSocket.State == WebSocketState.Open)

        {

            var result = await ws.WebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), _cts.Token);

            if (result.MessageType == WebSocketMessageType.Text)

            {

                var msg = Encoding.UTF8.GetString(buffer, 0, result.Count);

                Console.WriteLine($"收到消息: {msg}");

                // 示例:返回处理结果

                var response = $"已处理: {msg}";

                await ws.WebSocket.SendAsync(

                    new ArraySegment<byte>(Encoding.UTF8.GetBytes(response)),

                    WebSocketMessageType.Text,

                    true,

                    _cts.Token);

            }

        }

    }

}

// 启动示例

var server = new WebSocketServer();

await server.StartAsync("http://localhost:8080/ws/");

二、JavaScript客户端实现

class WebSocketClient {

    constructor(url) {

        this.url = url;

        this.socket = null;

        this.reconnectInterval = 3000;

    }

    connect() {

        this.socket = new WebSocket(this.url);

        this.socket.onopen = () => {

            console.log("连接已建立");

            this.heartbeat();

        };

        this.socket.onmessage = (e) => {

            console.log("服务端响应:", e.data);

        };

        this.socket.onclose = () => {

            setTimeout(() => this.connect(), this.reconnectInterval);

        };

    }

    heartbeat() {

        setInterval(() => {

            this.send(JSON.stringify({ type: "heartbeat" }));

        }, 30000);

    }

    send(data) {

        if (this.socket.readyState === WebSocket.OPEN) {

            this.socket.send(data);

        }

    }

}

// 使用示例

const client = new WebSocketClient("ws://localhost:8080/ws/");

client.connect();

// 发送业务消息

document.getElementById("sendBtn").addEventListener("click", () => {

    client.send(JSON.stringify({ 

        action: "chat", 

        content: "Hello WebSocket!" 

    }));

});

三、关键实现说明

?协议控制?

服务端通过HttpListener实现WebSocket握手协议?2

客户端通过WebSocket原生API建立连接?6

?心跳机制?

客户端每30秒发送心跳包维持连接?3

服务端自动响应心跳请求?4

?数据格式?

默认使用UTF-8编码传输文本消息?2

建议使用JSON格式结构化数据?1

?异常处理?

客户端实现自动重连机制?3

服务端通过CancellationToken安全终止连接?7

四、部署注意事项

?IIS兼容性?

在IIS中部署需启用WebSocket功能?8

建议配置web.config添加WebSocket支持模块?5

?防火墙设置?

确保服务端端口(如8080)对外开放?4

?性能优化?

高并发场景建议使用异步线程池处理连接?7

该方案已在物联网控制、实时聊天等场景验证可用性?13。


查看更多关于WebSocket协议应用实例的JAVASCRIPT+C#在.Net framework4.8框架下的详细内容...

  阅读:16次