【C#】WCF和TCP消息通信练习,实现聊天功能

这篇具有很好参考价值的文章主要介绍了【C#】WCF和TCP消息通信练习,实现聊天功能。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

WCF和TCP消息通信练习

客户端

MainWindow.xaml

主页面
【C#】WCF和TCP消息通信练习,实现聊天功能

<Window x:Class="Lab_5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Lab_5"
        mc:Ignorable="d"
        Title="主界面" Height="450" Width="800">
    <Grid>
        <Button Name="bt1" Content="同时启动两个客户端(测试用)" HorizontalAlignment="Left" Margin="259,150,0,0" VerticalAlignment="Top" Width="265" Height="27" Click="bt1_Click"/>
        <Button Name="bt2" Content="只启动一个客户端(实际情况)" HorizontalAlignment="Left" Margin="259,252,0,0" VerticalAlignment="Top" Width="265" Height="28" Click="bt2_Click"/>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Lab_5
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void StartWindow(string userName, int left, int top)
        {
            ChatCline w = new ChatCline();
            w.Left = left;
            w.Top = top;
            w.UserName = userName;
            w.Owner = this;
            w.Closed += (sender, e) => this.Activate();//关闭子窗体时激活父窗体
            w.Show();
        }

        private void bt1_Click(object sender, RoutedEventArgs e)
        {
            StartWindow("用户1", 0, 0);
            StartWindow("用户2", 400, 300);
        }

        private void bt2_Click(object sender, RoutedEventArgs e)
        {
            ChatCline w = new ChatCline();
            w.Owner = this;
            w.Closed += (sendObj, args) => this.Activate();
            w.Show();
        }
    }
}

ChatCline.xaml

聊天界面
【C#】WCF和TCP消息通信练习,实现聊天功能

<Window x:Class="Lab_5.ChatCline"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Lab_5"
        mc:Ignorable="d"
        Title="群聊客户端" Height="450" Width="800">
    <Grid>
        <TextBlock HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Text="用户名:" VerticalAlignment="Top" Height="28" Width="69" FontSize="14"/>
        <TextBox Name="textbox" HorizontalAlignment="Left" Height="28" Margin="84,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="217" FontSize="14"/>
        <Button Name="login" Content="登录" HorizontalAlignment="Left" Margin="333,10,0,0" VerticalAlignment="Top" Width="75" Height="28" FontSize="14" Click="login_Click"/>
        <Canvas Name="box" HorizontalAlignment="Left" Height="363" Margin="0,57,-0.4,0" VerticalAlignment="Top" Width="794">
            <TextBlock Canvas.Left="10" TextWrapping="Wrap" Text="在线用户" Canvas.Top="10" Height="24" Width="74" FontSize="14"/>
            <ListBox Name="listbox" Height="324" Canvas.Top="39" Width="84" FontSize="14"/>
            <TextBlock Canvas.Left="127" TextWrapping="Wrap" Text="对话信息" Canvas.Top="10" Height="24" Width="657" TextAlignment="Center" FontSize="14"/>
            <ListBox Name="listmessage" Height="252" Canvas.Left="104" Canvas.Top="39" Width="680" FontSize="14"/>
            <TextBlock Canvas.Left="104" TextWrapping="Wrap" Text="发言:" Canvas.Top="314" Height="27" Width="50" FontSize="14"/>
            <TextBox Name="messagebox" Height="27" Canvas.Left="154" TextWrapping="Wrap" Text="" Canvas.Top="314" Width="481" FontSize="14" KeyDown="messagebox_KeyDown"/>
            <Button Name="launch" Content="发送" Canvas.Left="679" Canvas.Top="314" Width="75" Height="27" FontSize="14" Click="launch_Click"/>
        </Canvas>

    </Grid>
</Window>

ChatCline.xaml.cs

using Lab_5.ServiceReference1;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Lab_5
{
    /// <summary>
    /// ChatCline.xaml 的交互逻辑
    /// </summary>
    public partial class ChatCline : Window,IService1Callback
    {
        public ChatCline()
        {
            InitializeComponent();
            this.Closing += ChatCline_Closing;
            box.Visibility = System.Windows.Visibility.Hidden;
        }

        private Service1Client client;

        public string UserName
        {
            get { return textbox.Text; }
            set { textbox.Text = value; }
        }

        private void ChatCline_Closing(object sender, CancelEventArgs e)
        {
            if (client != null)
            {
                client.Logout(UserName); 
                client.Close();
            }
        }

        private void AddMessage(string str)
        {
            TextBlock t = new TextBlock();
            t.Text = str;
            listmessage.Items.Add(t);
        }

        public void InitUsersInfo(string UsersInfo)
        {
            if (UsersInfo.Length == 0) return;
            string[] users = UsersInfo.Split('、');
            for (int i = 0; i < users.Length; i++)
            {
                listbox.Items.Add(users[i]);
            }
        }

        public void ShowLogin(string loginUserName)
        {
            if (loginUserName == UserName)
            {
                box.Visibility = System.Windows.Visibility.Visible;
            }
            listbox.Items.Add(loginUserName);
        }

        public void ShowLogout(string userName)
        {
            listbox.Items.Remove(userName);
        }

        public void ShowTalk(string userName, string message)
        {
            AddMessage(userName+"说: "+message);
        }

        private void login_Click(object sender, RoutedEventArgs e)
        {
            UserName = textbox.Text;
            InstanceContext context = new InstanceContext(this);
            client = new Service1Client(context);
            try
            {
                client.Login(textbox.Text);
                login.IsEnabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("与服务端连接失败:" + ex.Message);
                return;
            }
        }

        private void launch_Click(object sender, RoutedEventArgs e)
        {
            client.Talk(UserName, messagebox.Text);
            messagebox.Text = "";
        }


        private void messagebox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                client.Talk(UserName, messagebox.Text);
                messagebox.Text = "";
            }
        }
    }
}

服务端

Users.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WcfServiceLibrary1
{
    class Users
    {
        public string UserName { get; set; }
        public readonly IService1Callback callback;

        public Users(string userName, IService1Callback callback)
        {
            this.UserName = userName;
            this.callback = callback;
        }
    }
}

CC.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WcfServiceLibrary1
{
    class CC
    {
        public static List<Users> Users { get; set; }

        static CC()
        {
            Users = new List<Users>();
        }

        public static Users GetUser(string userName)
        {
            Users user = null;
            foreach (var v in Users)
            {
                if (v.UserName == userName)
                {
                    user = v;
                    break;
                }
            }
            return user;
        }
    }
}

IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfServiceLibrary1
{
    [ServiceContract(Namespace = "IService",
        CallbackContract = typeof(IService1Callback))]
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
    public interface IService1
    {

        // TODO: 在此添加您的服务操作
        [OperationContract(IsOneWay = true)]
        void Login(string userName);

        [OperationContract(IsOneWay = true)]
        void Logout(string userName);

        [OperationContract(IsOneWay = true)]
        void Talk(string userName, string message);
    }


    public interface IService1Callback
    {
        [OperationContract(IsOneWay = true)]
        void ShowLogin(string loginUserName);

        [OperationContract(IsOneWay = true)]
        void ShowLogout(string userName);

        [OperationContract(IsOneWay = true)]
        void ShowTalk(string userName, string message);

        [OperationContract(IsOneWay = true)]
        void InitUsersInfo(string UsersInfo);
    }

}

Service1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfServiceLibrary1
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Service1”。
    public class Service1 : IService1
    {
        public void Login(string userName)
        {
            OperationContext context = OperationContext.Current;
            IService1Callback callback = context.GetCallbackChannel<IService1Callback>();
            Users newUser = new Users(userName, callback);
            string str = "";
            for (int i = 0; i < CC.Users.Count; i++)
            {
                str += CC.Users[i].UserName + "、";
            }
            newUser.callback.InitUsersInfo(str.TrimEnd('、'));
            CC.Users.Add(newUser);
            foreach (var user in CC.Users)
            {
                user.callback.ShowLogin(userName);
            }
        }

        public void Logout(string userName)
        {
            Users logoutUser = CC.GetUser(userName);
            CC.Users.Remove(logoutUser);
            logoutUser = null;
            foreach (var user in CC.Users)
            {
                user.callback.ShowLogout(userName);
            }
        }

        public void Talk(string userName, string message)
        {
            Users user = CC.GetUser(userName);
            foreach (var v in CC.Users)
            {
                v.callback.ShowTalk(userName, message);
            }
        }
    }
}

实验结果

【C#】WCF和TCP消息通信练习,实现聊天功能文章来源地址https://www.toymoban.com/news/detail-478431.html

到了这里,关于【C#】WCF和TCP消息通信练习,实现聊天功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • C# Modbus通信从入门到精通(22)——Modbus TCP(0x01功能码与C#代码实现)

    使用该功能码能从远程地址中读取1到2000个线圈的状态,每个线圈的状态只能是0或者1,读取的线圈数量由主站读取时指定。 MBAP报文头格式如下: 更详细的格式如下: MBAP报文头+功能码+起始地址高位+起始地址低位+线圈数量高位+线圈数量低位,一共12个字节。 更详细的格式

    2024年02月07日
    浏览(43)
  • Unity-TCP-网络聊天功能(四): 消息粘包、心跳机制保活(心跳包)、断线重连

    bug1:下线后,如果发送多条消息,在客户端上线时,一瞬间接收到,效果如同粘包,需要拆包。举例,连续发送三条160长度消息,可能实际显示2条消息,原因,第三条消息和第二条消息粘包,第二条消息长度变为320,但是Receive方法没有考虑这个问题,相当于这段代码只运行

    2024年02月11日
    浏览(29)
  • 开源在线客服系统-客服系统历史消息记录功能-点击加载历史聊天记录-分页展示历史消息功能实现

    之前开发的开源在线客服系统gofly,访客端一直没有展示历史聊天记录,最近抽时间给加上了 实现的效果就是,访客刚进聊天界面,如果存在历史记录,按5条分页,默认查询加载5条聊天记录。 如果历史记录超过5条,顶部出现 “点击加载更多” 按钮,点击按钮就分页查询历

    2023年04月12日
    浏览(30)
  • ModbusRTU\TCP消息帧解析(C#实现报文发送与解析)

    PLC寄存器中存储(整型和无符号整型:2字节。长整型:4字节。单精度浮点数:4字节。双精度浮点数:8字节),我们只要知道数据类型,是2个字节一截取,还是4个字节 ,对接收到的报文进行字节截取然后编码成str就行 向PLC中写入Float,float占4个字节=2个寄存器,所以要使用

    2024年02月03日
    浏览(39)
  • JAVA Socket实现实时接收TCP消息,让你的服务端通信更高效!

    本文主要介绍如何利用socket实现实时接收服务端发送的TCP消息。 目录 一、需要掌握 二、程序源码 三、运行演示 网络调试助手下载:https://www.aliyundrive.com/s/6Y8L7Wv5sT6 网络通信协议的理解:JAVA socket是基于TCP/IP协议实现的,需要对TCP/IP协议有一定的了解,包括TCP连接的建立、数

    2024年02月11日
    浏览(32)
  • 蓝牙聊天App设计3:Android Studio制作蓝牙聊天通讯软件(完结,蓝牙连接聊天,结合生活情景进行蓝牙通信的通俗讲解,以及代码功能实现,内容详细,讲解通俗易懂)

    前言:蓝牙聊天App设计全部有三篇文章(一、UI界面设计,二、蓝牙搜索配对连接实现,三、蓝牙连接聊天),这篇文章是:三、蓝牙连接聊天。 课程1:Android Studio小白安装教程,以及第一个Android项目案例“Hello World”的调试运行 课程2:蓝牙聊天App设计1:Android Studio制作蓝

    2024年02月12日
    浏览(27)
  • C#上位机基础学习_基于SOCKET实现与PLC服务器的TCP通信(一)

    测试软件: TIA PORTAL V15.1 S7-PLCSIM ADVANCED V3.0 Visual Studio 2019 如下图所示,打开S7-PLCSIM ADVANCED V3.0仿真软件,新键一个实例,设置仿真PLC的IP地址等参数,然后点击Start激活PLC, 如下图所示,激活PLC后,可以看到已经存在一个实例, 如下图所示,打开TIA PORTAL V15.1,新建一个项目,

    2023年04月15日
    浏览(32)
  • QT C++ 基于TCP通信的网络聊天室

    .ui .pro 在pro文件中添加network库 .h .main .cpp .ui .pro 在pro文件中添加network库 .h .main .cpp        

    2024年02月09日
    浏览(44)
  • TCP发送数据、接受数据及TCP通信程序练习

    目录 一、TCP发送数据 二、TCP接收数据 三、TCP通信程序练习 Java中的TCP通信: Java对于基于TCP协议的网络提供了良好的封装,使用Socket对象来代表两端的通信端口,并通过Socket产生IO流来进行网络通信 Java为客户端提供了Socket类,为服务端提供了ServerSocket类 构造方法: 方法名

    2023年04月09日
    浏览(26)
  • c#——WCF和HTTP文件传输实验

    (1)掌握HTTP协议下WCF服务应用程序构建方法。 (2)掌握WCF客户端和服务端的消息交换模式。 (3)掌握协定的设计及实现方法。 (4)熟悉WCF和HTTP的相关绑定设置。 (5)掌握流的读写操作方法。 在同一个解决方案中,分别编写服务端程序和客户端程序,利用HTTP和流传输实

    2024年02月07日
    浏览(34)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包