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)

References

Top Articles
2 Pm Bst
Victoria Snooks Fapello
Po Box 7250 Sioux Falls Sd
Terrorist Usually Avoid Tourist Locations
Goodbye Horses: The Many Lives of Q Lazzarus
Evil Dead Rise Showtimes Near Massena Movieplex
Mcoc Immunity Chart July 2022
A Fashion Lover's Guide To Copenhagen
Love Compatibility Test / Calculator by Horoscope | MyAstrology
fltimes.com | Finger Lakes Times
Saw X | Rotten Tomatoes
Fredericksburg Free Lance Star Obituaries
Directions To O'reilly's Near Me
“In my day, you were butch or you were femme”
Saberhealth Time Track
Wal-Mart 140 Supercenter Products
Costco Gas Foster City
R Cwbt
Christina Steele And Nathaniel Hadley Novel
I Saysopensesame
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Theater X Orange Heights Florida
Teen Vogue Video Series
Pocono Recird Obits
Restored Republic June 16 2023
Rgb Bird Flop
Stickley Furniture
Spirited Showtimes Near Marcus Twin Creek Cinema
Tripcheck Oregon Map
Human Unitec International Inc (HMNU) Stock Price History Chart & Technical Analysis Graph - TipRanks.com
Desirulez.tv
Cheap Motorcycles Craigslist
Wow Quest Encroaching Heat
One Credit Songs On Touchtunes 2022
Craigslist Albany Ny Garage Sales
Why The Boogeyman Is Rated PG-13
Why Gas Prices Are So High (Published 2022)
Pawn Shop Open Now
Directions To Advance Auto
Oxford House Peoria Il
Busted Newspaper Campbell County KY Arrests
Wayne State Academica Login
Bob And Jeff's Monticello Fl
Lacy Soto Mechanic
Wordle Feb 27 Mashable
Celsius Claims Agent
Squalicum Family Medicine
Gas Buddy Il
Bellelement.com Review: Real Store or A Scam? Read This
Walmart Front Door Wreaths
The 5 Types of Intimacy Every Healthy Relationship Needs | All Points North
Guidance | GreenStar™ 3 2630 Display
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 5662

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.