做个小工具-WebSocket客户端

这篇具有很好参考价值的文章主要介绍了做个小工具-WebSocket客户端。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

由于工作的原因经常需要用到一些socket,串口等调试工具,但是好多工具要么只有其中几个或者各种收费,不断提醒捐助等。所以还是自己做一个吧。毕竟也不复杂。今天先做个WebSocket客户端。WebSocket使用了开源组件WatsonWebsocket。

  1. 先上图
    websocket小工具,.net,websocket,microsoft,网络协议
  2. View的代码
<local:PageWithId x:Class="ToolsAssistant.Views.WebSocketClientView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:ToolsAssistant.Views" xmlns:viewmodels="clr-namespace:ToolsAssistant.ViewModels" d:DataContext="{d:DesignInstance Type=viewmodels:WebSocketClientViewModel}"
      mc:Ignorable="d" 
      d:DesignHeight="450" d:DesignWidth="800" Unloaded="Page_Unloaded" Loaded="Page_Loaded"
      Title="WebServerClientView" Background="White">
    
    <Grid>
        <Grid.Resources>
            <Style x:Key="btn_style" TargetType="Button">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Content, ElementName=btn_connect}" Value="连接">
                        <Setter Property="IsEnabled" Value="False"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Content, ElementName=btn_connect}" Value="断开">
                        <Setter Property="IsEnabled" Value="true"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
            <Style x:Key="radio_style" TargetType="RadioButton">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Content, ElementName=btn_connect}" Value="连接">
                        <Setter Property="IsEnabled" Value="False"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Content, ElementName=btn_connect}" Value="断开">
                        <Setter Property="IsEnabled" Value="true"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Border BorderThickness="1" BorderBrush="Gray" Margin="3" CornerRadius="5" Grid.Row="0">
            <StackPanel  Orientation="Horizontal">
                <Label Content="ws://" Margin="3" VerticalContentAlignment="Center"></Label>
                <TextBox Text="{Binding Url}" Margin="3" Width="200" VerticalContentAlignment="Center"/>
                <Button x:Name="btn_connect" Margin="3" Content="{Binding ConnectString}" Width="60" Command="{Binding ConnectCommand}">
                </Button>
            </StackPanel>
        </Border>
        <Border BorderThickness="1" BorderBrush="Gray" Margin="3" CornerRadius="5" Grid.Row="1">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="40"/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <StackPanel Grid.Row="0" Orientation="Horizontal">
                    <Button Content="发送" Command="{Binding SendCommand}" Width="60" Margin="3" Style="{StaticResource btn_style}">
                    </Button>
                    <Button Content="清空" Command="{Binding ClearSendCommand}" Width="60" Margin="3" Style="{StaticResource btn_style}"/>
                    <RadioButton Content="UTF8" Margin="3" VerticalContentAlignment="Center"  IsChecked="{Binding IsUTF8}" Style="{StaticResource radio_style}"/>
                    <RadioButton Content="ASCII" Margin="3" VerticalContentAlignment="Center" IsChecked="{Binding IsASCII}" Style="{StaticResource radio_style}" />
                    <RadioButton Content="HEX" Margin="3" VerticalContentAlignment="Center" IsChecked="{Binding IsHex}" Style="{StaticResource radio_style}"/>
                </StackPanel>
                <ScrollViewer Grid.Row="1" Margin="3">
                    <TextBox Text="{Binding SendStr}"></TextBox>
                </ScrollViewer>
            </Grid>
        </Border>
        <Border BorderThickness="1" BorderBrush="Gray" Margin="3" CornerRadius="5" Grid.Row="2">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="40"/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <StackPanel Grid.Row="0" Orientation="Horizontal">
                    <Button Content="清空" Command="{Binding ClearRecieveCommand}" Width="60" Margin="3" Style="{StaticResource btn_style}"/>
                    <RadioButton Content="UTF8" Margin="3" VerticalContentAlignment="Center" IsChecked="{Binding IsUTF8}" Style="{StaticResource radio_style}"/>
                    <RadioButton Content="ASCII" Margin="3" VerticalContentAlignment="Center" IsChecked="{Binding IsASCII}" Style="{StaticResource radio_style}"/>
                    <RadioButton Content="HEX" Margin="3" VerticalContentAlignment="Center" IsChecked="{Binding IsHex}" Style="{StaticResource radio_style}"/>
                </StackPanel>
                <ScrollViewer Grid.Row="1" Margin="3">
                    <TextBox Text="{Binding RecieveStr}"></TextBox>
                </ScrollViewer>
            </Grid>
        </Border>
    </Grid>
</local:PageWithId>

  1. ViewModel的代码
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using ToolsAssistant.Services;

namespace ToolsAssistant.ViewModels
{
    public class WebSocketClientViewModel: ObservableObject
    {
        #region props
        private string _ConnectString = "连接";
        public string ConnectString { set => SetProperty(ref _ConnectString, value); get => _ConnectString; }

        private string _SendStr;
        public string SendStr { set => SetProperty(ref _SendStr, value); get => _SendStr; }

        private string _RecieveStr;
        public string RecieveStr { set => SetProperty(ref _RecieveStr, value); get => _RecieveStr; }

        private bool _IsUTF8 = true;
        public bool IsUTF8 {
            set
            {
                SetProperty(ref _IsUTF8, value);
                InitEncoder();
            }
            get => _IsUTF8; }

        private bool _IsASCII = false;
        public bool IsASCII {
            set
            {
                SetProperty(ref _IsASCII, value);
                InitEncoder();
            }
            get => _IsASCII; }

        private bool _IsHex = false;
        public bool IsHex {
            set
            {
                SetProperty(ref _IsHex, value);
                InitEncoder();
            }
            get => _IsHex; }

        private string _Url = "127.0.0.1:8888";
        public string Url { set => SetProperty(ref _Url, value); get => _Url; }
        #endregion
        #region commands
        public RelayCommand SendCommand { set; get; }
        public RelayCommand ClearSendCommand { set; get; }
        public RelayCommand ClearRecieveCommand { set; get; }
        public RelayCommand ConnectCommand { set; get; }
        #endregion
        #region methods
        protected readonly ILogger<WebSocketClientViewModel> _logger;
        protected readonly IWebSocketClient _client;
        public WebSocketClientViewModel()
        {
            _logger = App.Current.Services.GetService<ILogger<WebSocketClientViewModel>>();
            _client = App.Current.Services.GetService<IWebSocketClient>();
            Init();
        }

        private void Init()
        {
            SendCommand = new RelayCommand(OnSendCommand);
            ClearSendCommand = new RelayCommand(OnClearSendCommand);
            ClearRecieveCommand = new RelayCommand(OnClearRecieveCommand);
            ConnectCommand = new RelayCommand(OnConnectCommand);

            _client.ConnectEvent += ConnectEvent;

        }

        private void InitEncoder()
        {
            if(IsUTF8)
            {
                _client.SetEncording(EncordingType.Utf8);
            }
            if (IsASCII)
            {
                _client.SetEncording(EncordingType.ASCII);
            }
            if (IsHex)
            {
                _client.SetEncording(EncordingType.Hex);
            }
        }

        private void ConnectEvent(string ipPort, bool isConnect)
        {
            if(isConnect)
            {
                ConnectString = "断开";
                InitEncoder();
            }
            else
            {
                ConnectString = "连接";
            }
        }

        private void OnConnectCommand()
        {
            try
            {
                if(ConnectString == "连接")
                {
                    _client.Connect(Url);
                }
                else
                {
                    _client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                MessageBox.Show(ex.ToString());
            }
        }

        private void OnClearRecieveCommand()
        {
            try
            {
                RecieveStr = "";
            }catch(Exception ex)
            {
                _logger.LogError(ex.ToString());
                MessageBox.Show(ex.ToString());
            }
        }

        private void OnClearSendCommand()
        {
            try
            {
                SendStr = "";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                MessageBox.Show(ex.ToString());
            }
        }

        private void OnSendCommand()
        {
            try
            {
                if(string.IsNullOrEmpty(SendStr))
                {
                    throw new Exception("发送内容不允许为空");
                }

                _client.SendData(SendStr);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                MessageBox.Show(ex.ToString());
            }
        }
        #endregion
    }
}

  1. servervice的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WatsonWebsocket;

namespace ToolsAssistant.Services
{
    internal class WebSocketClient : IWebSocketClient
    {
        private WatsonWsClient _client = null;

        private EncordingType _encordingType = EncordingType.Utf8;

        public event EventHandlers.DataRecievedEventHandler DataRecievedEvent;
        public event EventHandlers.ConnectEventHandler ConnectEvent;

        public void Connect(string ipPort)
        {
            if(_client == null||!_client.Connected)
            {
                _client = new WatsonWsClient(new Uri($"ws://{ipPort}"));
            }else
            {
                _client.Stop();
                _client = new WatsonWsClient(new Uri($"ws://{ipPort}"));
            }

            _client.ServerConnected += ServerConnected;
            _client.MessageReceived += MessageReceived;
            _client.ServerDisconnected += ServerDisconnected;

            _client.Start();
        }

        private void ServerDisconnected(object sender, EventArgs e)
        {
            ConnectEvent?.Invoke(null, false);
        }

        private void MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            try
            {
                string data = "";
                switch(_encordingType)
                {
                    case EncordingType.Utf8:
                        data = Encoding.UTF8.GetString(e.Data);
                        break;
                    case EncordingType.ASCII:
                        data = Encoding.ASCII.GetString(e.Data);
                        break;
                    case EncordingType.Hex:
                        for(int i=0;i<e.Data.Length;i++)
                        {
                            data += Convert.ToString(e.Data[i],16)+" ";
                        }
                        break;
                }
                DataRecievedEvent?.Invoke(e.IpPort,data);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void ServerConnected(object sender, EventArgs e)
        {
            ConnectEvent?.Invoke(null, true);
        }

        public void Disconnect()
        {
            if(_client.Connected)
            {
                _client.Stop();
                ConnectEvent?.Invoke(null, false);
            }
        }

        public void SetEncording(EncordingType encordingType)
        {
            _encordingType = encordingType;
        }

        public void SendData(string data)
        {
            byte[] dataBytes;
            switch (_encordingType)
            {
                case EncordingType.ASCII:
                    dataBytes = Encoding.ASCII.GetBytes(data.Replace(" ",""));
                    break;
                case EncordingType.Hex:
                    var lst = data.Split(" ");
                    dataBytes = new byte[lst.Length];
                    for (int i = 0; i < lst.Length; i++)
                    {
                        dataBytes[i] = Convert.ToByte(lst[i], 16);
                    }
                    break;
                default: //EncordingType.Utf8
                    dataBytes = Encoding.UTF8.GetBytes(data);
                    break;
            }

            _client.SendAsync(dataBytes);
        }
    }
}

其他的代码就不列出来了,见代码仓库文章来源地址https://www.toymoban.com/news/detail-552468.html

到了这里,关于做个小工具-WebSocket客户端的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot WebSocket做客户端

    常见的都是springboot应用做服务,前端页面做客户端,进行websocket通信进行数据传输交互。但其实springboot服务也能做客户端去连接别的webSocket服务提供者。 刚好最近在项目中就使用到了,需求背景大概就是我们作为一个java段应用需要和一个C语言应用进行通信。在项目需求及

    2024年02月11日
    浏览(35)
  • WebSocket 实现长连接及通过WebSocket获取客户端IP

    WebSocket 是一种支持双向通讯的网络通信协议。 实现过程: 1 添加ServerEndpointExporter配置bean 2 实现过程 需求是通过WebSocket,建立长连接,并获取当前在线的人数。通过Websocket 不断发送消息,建立长连接,给Session续命。我是通过MAC地址,区分不同的设备,因为我的需求中需要一

    2024年02月09日
    浏览(42)
  • 快速搭建springboot websocket客户端

    WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。 HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。 HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。 浏览器通过 JavaSc

    2024年02月06日
    浏览(49)
  • SpringBoot+WebSocket实现服务端、客户端

    小编最近一直在使用springboot框架开发项目,毕竟现在很多公司都在采用此框架,之后小编也会陆续写关于springboot开发常用功能的文章。 什么场景下会要使用到websocket的呢? websocket主要功能就是实现网络通讯,比如说最经典的客服聊天窗口、您有新的消息通知,或者是项目与

    2024年02月13日
    浏览(37)
  • python用websockets创建服务端websocket创建客户端

    服务端 客户端

    2024年02月22日
    浏览(42)
  • 实现c++轻量级别websocket协议客户端

    因以前发过这个代码,但是一直没有整理,这次整理了一下,持续修改,主要是要使用在arm的linux上,发送接收的数据压缩成图片发送出去。 要达到轻量websocket 使用,必须要达到几个方面才能足够简单, 1、不用加入其他的库 2、只需要使用头文件包含就可以 3、跨平台 如果

    2024年02月12日
    浏览(31)
  • JAVA使用WebSocket实现多客户端请求

    工作前提:两个服务之间实现聊天通讯,因为介于两个服务,两个客户端 方案1:多个服务端,多个客户端,使用redis把用户数据ip进行存储,交互拿到redis数据进行推送 方案2: 一个服务端,多个客户端,拿到客户端的id和需要推送的id进行拼接存储 此文章使用的是方案2 1. 引

    2024年02月11日
    浏览(34)
  • Java WebSocket 获取客户端 IP 地址

    在开发 Web 应用程序时,我们通常需要获取客户端的 IP 地址用于日志记录、身份验证、限制访问等操作。当使用 WebSocket 协议时,我们可以使用 Java WebSocket API 来获取客户端的 IP 地址。 本文将介绍如何使用 Java WebSocket API 获取客户端 IP 地址,以及如何在常见的 WebSocket 框架中

    2024年02月05日
    浏览(33)
  • C# WebSocket 客户端 使用 TouchSocket WebSocketClient

    由于涉及到连接某音的弹幕数据,所以需要WebSocket,百度了一圈,有C#原生的WebSocket,看了看,看不懂,无奈换一个,TouchSocket来到了我的面前,网上对于这个插件的评价较高,所以使用之。结果,一堆问题之。唉。抄袭这么难吗? 如果由TouchSocket开发服务端,并且用TouchSoc

    2024年02月12日
    浏览(41)
  • SpringBoot2.0集成WebSocket,多客户端

    适用于单客户端,一个账号登陆一个客户端,登陆多个客户端会报错 The remote endpoint was in state [TEXT_FULL_WRITING]  这是因为此时的session是不同的,只能锁住一个session,解决此问题的方法把全局静态对象锁住,因为账号是唯一的

    2024年02月10日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包