wcf双工通信聊天室(wpf+c#)-爱代码爱编程 (2024)

目录

WCF部分

Service1.svc.cs源码

IService1.cs源码

Use类

WPF部分

MainWindow.xaml.cs源码

MainWindow.xaml源码

操作

不足

要用双工通信先配置文件在Web.config那里,怎么配置自行搜索。

关于WCF和WPF的服务引用可以看这篇文章WPF调WCF服务端

Service1.svc.cs源码

using GobangGameWcfService;using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.ServiceModel.Web;using System.Text;namespace WcfService_ChatService{ // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Service1”。 // 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 Service1.svc 或 Service1.svc.cs,然后开始调试。 public class Service1 : IService1 { public Service1() { if (Users.userList == null) Users.userList = new List<User>(); } private IChatServiceCallback callback; public void Login(string username) { OperationContext context = OperationContext.Current; callback = context.GetCallbackChannel<IChatServiceCallback>(); User newUser = new User(username, callback); newUser.userName = username; foreach (var userone in Users.userList) { if(newUser.userName == userone.userName) { callback.ShowWrongLogin(userone.userName); return; } } Users.userList.Add(newUser); foreach (var usertwo in Users.userList) { usertwo.callback.ShowLogin(username, Users.userList.Count); } //callback.ShowUserList(Users.userList); } public void Logout(string userName) { User removeUser = null; foreach (User one in Users.userList) { if (one.userName == userName) { removeUser = one; break; } } if(removeUser == null) { callback.ShowWrongLogout(userName); return; } Users.userList.Remove(removeUser); foreach (var user in Users.userList) { user.callback.ShowLogout(userName, Users.userList.Count); } } public void sendInfo(string info , string userName) { foreach (var user in Users.userList) { user.callback.ShowSendInfo(info, userName); } } public class Users { public static List<User> userList; } /* public class User { public string userName; public DateTime loginTime; public User(string userName) { this.userName = userName; } } public class Users { public static List<User> userList; }*/ }}

IService1.cs源码

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.ServiceModel.Web;using System.Text;using static WcfService_ChatService.Service1;namespace WcfService_ChatService{ [ServiceContract(CallbackContract = typeof(IChatServiceCallback))] //服务端 public interface IService1 { [OperationContract(IsOneWay = true)] void Login(string userName); [OperationContract(IsOneWay = true)] void sendInfo(string info,string userName); [OperationContract(IsOneWay = true)] void Logout(string userName); }/* [DataContract] public class User { [DataMember]public string userName { get; set; } public readonly IChatServiceCallback callback //[DataMember] public DateTime loginTime{ get; set; } } */ //客户端 public interface IChatServiceCallback { [OperationContract(IsOneWay = true)] void ShowLogin(string userName, int userCount); [OperationContract(IsOneWay = true)] void ShowSendInfo(string info , string infousername); [OperationContract(IsOneWay = true)] void ShowLogout(string userName, int userCount); [OperationContract(IsOneWay = true)] void ShowWrongLogin(string userName); [OperationContract(IsOneWay = true)] void ShowWrongLogout(string userName); //[OperationContract(IsOneWay = true)] //void ShowUserList(List<User> usersList); }}

Use类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using WcfService_ChatService;namespace GobangGameWcfService{ public class User { /// <summary>登录的用户名</summary> public string userName; public DateTime loginTime; public readonly IChatServiceCallback callback; public User(string userName, IChatServiceCallback callback) { this.userName = userName; this.callback = callback; } }}

MainWindow.xaml.cs源码

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;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.Navigation;using System.Windows.Shapes;using WpfApp_ChatClient2.ServiceReference1;namespace WpfApp_ChatClient2{ /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window, IService1Callback { public MainWindow() { InitializeComponent(); this.Closing += Window_Closing; this.btnLogout.IsEnabled = false; this.btnSend.IsEnabled = false; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { client.Logout(UserName); e.Cancel = false; } public string UserName; private Service1Client client; //登录 private void btnLogin_Click(object sender, RoutedEventArgs e) { UserName = textBoxUserName.Text; if (textBoxUserName.Text == String.Empty) { MessageBox.Show("用户名不能为空!!!"); return; } InstanceContext context = new InstanceContext(this); client = new Service1Client(context); client.Login(textBoxUserName.Text); serviceTextBlock.Text = "服务端地址:" + client.Endpoint.ListenUri.ToString(); this.btnLogin.IsEnabled = false; this.btnLogout.IsEnabled = true; this.btnSend.IsEnabled = true; } //退出 private void btnLogout_Click(object sender, RoutedEventArgs e) { if (textBoxUserName.Text == String.Empty) { MessageBox.Show("用户名不能为空!!!"); return; } client.Logout(UserName); userscount.Text = "在线人数:0"; this.btnLogin.IsEnabled = true; this.btnLogout.IsEnabled = false; this.btnSend.IsEnabled = false; } //发送消息 private void btnSend_Click(object sender, RoutedEventArgs e) { if (textBoxSend.Text == String.Empty) { MessageBox.Show("发送的消息不能为空!!!"); return; } client.sendInfo(textBoxSend.Text, UserName); textBoxSend.Clear(); } //显示用户登录 public void ShowLogin(string loginUsername, int userCount) { listBoxMessage.Items.Add(loginUsername + "进入大厅。"); userscount.Text = "在线人数:" + userCount.ToString(); } //显示输入的消息 public void ShowSendInfo(string info ,string infousername) { listBoxMessage.Items.Add(infousername + ": " + info); } //显示用户退出 public void ShowLogout(string userName, int userCount) { listBoxMessage.Items.Add(userName + "退出大厅。"); userscount.Text = "在线人数:" + userCount.ToString(); } public void ShowWrongLogin(string username) { MessageBox.Show("用户" + username + "已经存在"); } public void ShowWrongLogout(string username) { MessageBox.Show("用户" + username + "已经退出"); } private void textBoxSend_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { this.btnSend_Click(sender, e); } } /* public class User { public string userName { get; set; } } //显示在线用户 public void ShowUserList(User[] usersList) { this.dataGrid.ItemsSource = usersList; } public void ShowUserList(Service1User[] usersList) { this.dataGrid.ItemsSource = usersList; } */ private void btnReturn_Click(object sender, RoutedEventArgs e) { return; } }}

MainWindow.xaml源码

<Window x:Class="WpfApp_ChatClient.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:WpfApp_ChatClient" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="40"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="150"></ColumnDefinition> <ColumnDefinition Width="500"></ColumnDefinition> <ColumnDefinition Width="*"></ColumnDefinition> </Grid.ColumnDefinitions> <DockPanel Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3" Background="Cornsilk" Margin="5 5 0 5"> <Label Content="用户名:"/> <TextBox Name="textBoxUserName" Width="100" VerticalAlignment="Center"/> <Button Name="btnLogin" Content="登录" Width="60" Margin="10 0 10 0" Click="btnLogin_Click"/> <Button Name="btnLogout" Content="退出" Width="60" Margin="10 0 10 0" Click="btnLogout_Click"/> <TextBlock Name="serviceTextBlock" Text="服务端地址:" Margin="5 0 0 0" VerticalAlignment="Center"/> </DockPanel> <Grid Name="ChatRooms" Grid.Row="1" Grid.Column="0"> <Grid.RowDefinitions> <RowDefinition Height="20"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <TextBlock Grid.Row="0" Text="聊天室" Background="Beige" TextAlignment="Center"></TextBlock> <Grid Grid.Row="1" > <ListBox Name="listBoxRooms" Background="AntiqueWhite" ScrollViewer.VerticalScrollBarVisibility="Visible"/> </Grid> </Grid> <Grid Name="chatRoom" Grid.Row="1" Grid.Column="1"> <Grid.RowDefinitions> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="30"></RowDefinition> </Grid.RowDefinitions> <ListBox Name="listBoxMessage" Background="White" Grid.Row="0" ScrollViewer.VerticalScrollBarVisibility="Visible"/> <DockPanel Grid.Row="1" Background="AliceBlue" Margin="0 5 0 5" > <Button Name="btnReturn" Content="返回聊天大厅" Margin="5 0 0 0" Width="80" Click="btnReturn_Click"/> <TextBlock Text="聊天:" Margin="5 0 0 0 " DockPanel.Dock="Left" VerticalAlignment="Center"/> <Button Name="btnSend" Content="发送" Width="40" DockPanel.Dock="Right" Margin="5 0 5 0" Click="btnSend_Click"/> <TextBox Name="textBoxSend" KeyDown="textBoxSend_KeyDown"/> </DockPanel> </Grid> <Grid Name="chatUser" Grid.Row="1" Grid.Column="2"> <Grid.RowDefinitions> <RowDefinition Height="20"/> <RowDefinition Height="20"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <TextBlock Name="userscount" Grid.Row="0" Text="在线人数: 0" Background="Beige" TextAlignment="Center"/> <DataGrid Name="dataGrid" Grid.Row="1" VerticalAlignment="Bottom" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding userName}" ClipboardContentBinding="{x:Null}" Header="在线用户"/> <!-- <DataGridTextColumn Binding="{Binding loginTime}" ClipboardContentBinding="{x:Null}" Header="登录时间"/>--> </DataGrid.Columns> </DataGrid> <ListBox Name="listBoxUsers" Grid.Row="2" Padding=" 0 5 0 0" ScrollViewer.VerticalScrollBarVisibility="Visible"/> </Grid> </Grid></Window>

界面如下

wcf双工通信聊天室(wpf+c#)-爱代码爱编程 (1)

操作

wcf双工通信聊天室(wpf+c#)-爱代码爱编程 (2)

wcf双工通信聊天室(wpf+c#)-爱代码爱编程 (3)

wcf双工通信聊天室(wpf+c#)-爱代码爱编程 (4)

wcf双工通信聊天室(wpf+c#)-爱代码爱编程 (5)

1.在线用户列表没显示出来;

2.私聊还没完成,点击用户列表里面的用户可以新开一个界面然后聊天,返回大厅那个按钮就没用到;

点赞超过100就更新私聊功能

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/qq_63369996/article/details/130396365

wcf双工通信聊天室(wpf+c#)-爱代码爱编程 (2024)
Top Articles
Mejores Apartahoteles en Sapporo | Apart Hotels Hq
Ikuti Jejak NU, Muhammadiyah Akhirnya Terima Izin Tambang, Jokowi Beri Ketegasan: Kita Sudah Putuskan itu
Randolf Spellshine
Huggies Size 4 Walgreens
Dirty South Swag Review | BatDigest.com
Giant Key Osrs
"Rainbow Family" will im Harz bleiben: Hippie-Camp bis Anfang September geplant
Cognitive Function Test Potomac Falls
The biggest intelligence leaks in US history
Lebenszahl 8: Ihre wirkliche Bedeutung
Dirty Old Man Birthday Meme
1800Comcast
Osrs Mahogany Homes Calc
Juanita Swink Hudson
Does Publix Have Sephora Gift Cards
Meridamoonbeams
Syracuse Deadline
Dash Ag Grid
Eros Indy
G122 Pink Pill
Chittenden County Family Court Schedule
Clarkson Eyecare hiring Optometrist - Fredericksburg, VA in Fredericksburg, VA | LinkedIn
Hca Florida Middleburg Emergency Reviews
Vidant My Chart Login
Student Exploration Gravity Pitch
Funny Shooter Unblocked
Roundpoint Mortgage Mortgagee Clause
REGULAMENTUL CAMPANIEI "Extra Smart Week" valabil in perioada 12-18 septembrie 2024
Mark Rosen announces his departure from WCCO-TV after 50-year career
14314 County Road 15 Holiday City Oh
Palmer Santin Funeral Home Fullerton Nebraska Obituaries
Ansos Umm
8.7 Increase Of 841
Ny Trapping Forum
Craigslist Labor Gigs Albuquerque
Ups Store Laptop Box
Www Spherionnetwork.com
Sessional Dates U Of T
2005 Lund Boat For Sale in Ham Lake, MN Lot #67597***
Puppies For Sale in Netherlands (98) | Petzlover
Bfads 2022 Walmart
Glyph Of The Trusted Steed
Sport Clip Hours
Lol Shot Io Unblocked
Acceltrax Sycamore Services
Cranes for sale - used and new - TrucksNL
Telegram No Limit Groups - Telegram Rocket
The Marietta Times Obituaries
Netdania.com Gold
La tarifa "Go Hilton" para los amigos y familiares de los miembros del equipo - Lo que debe saber
Democrat And Chronicle Obituaries For This Week
Henry Ford Connect Email
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated:

Views: 6654

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.