Creating A WPF Chat Client Server Application(一)



Creating A WPF Chat Client Server Application(一)
本文译自:http://www.networkcomms.net/creating-a-wpf-chat-client-server-application/

Note: This tutorial is fairly extensive, if you are after something shorter please also see our Getting Started and How To Create a Client Server Application In Minutes tutorials.
译:注:本教程知识面较广较深,如果你想看简单和浅显的,可以看《Getting Started》 和《How To Create a Client Server Application In Minutes》。

Note2: This example is included, and has been significantly extended to demonstrate further features, in the examples bundle included in the package downloads.
译:注2:本例涵盖了很多功能,下载包中有本例源码。

Before we get started ensure you have Visual Studio 2010 Express or later installed, which should come with .Net 4 or later.
译:在开工之前,确保你的电脑上有VS2010,且包含微软Net4及以上框架。

1. Create Visual Studio Project
•Create a new visual studio solution containing a Visual C# ‘WPF Application‘ project naming it ‘WPFChatExample‘
•Right click on the project just created and select ‘Properties‘. Ensure the ‘Target Framework‘ is ‘.NET Framework 4‘ and not ‘.NET Framework 4 Client Profile‘. You should now have something that looks like this.
译:
1、创建VS Project
    创建“C#”、“WPF Application”解决方案,名字为“WPFChatExample”
    右击刚刚建立的project,击“属性”快捷菜单命令,在弹出的对话框中确保“Target Framework”是“.NET Framework 4”,而不是“.NET Framework 4 Client Profile”



2. Add NetworkComms .Net DLL to Project
•The NetworkComms.Net download package contains DLLs for all supported platforms but we are only interested in the Net40 > Release > Complete DLL. Copy this DLL to the same location as the solution we created in step 1.
•We now need to add a project reference to the NetworkComms .Net DLL we just added. Right click on the ‘WPFChatExample‘ project and select ‘Add Reference…‘. Within the window that opens select the Browse tab and select the DLL we just added.
•If you expand the ‘References‘ folder within the project you should now see the NetworkComms .Net reference you just added like this:
译:
2、添加[NetworkComms .Net DLL]到Project   
    Copy“ Net40 > Release > Complete DLL”下的文件到解决方案目录。
    右击“WPFChatExample”,击“添加 引用...”快捷菜单命令,在弹出的对话框中,点击“浏览”tab页,然后将这些dll文件添加选择进来。



3. Add WPF Elements
•We need to add the text boxes and buttons that we intend to interact with to the WPF layout. To get started double click the ‘MainWindow.xaml‘ file so that it opens in the main viewer:
译:
3、配置WPF元素
    双击“MainWindow.xaml”文件,打开设计界面,在界面上从工具箱里拖些text boxes和buttons,用于人机交互用。
 •If you wanted to you could now add each individual text box and button by hand. To save a little time however we have provided a base layout that you can copy and paste. Copy and paste the following code to replace ALL EXISTING code in the XAML view of ‘MainWindow.xaml‘:
为了节省时间,我们提供了代码,将这些代码全替“MainWindow.xaml”即可。

<Window x:Class="WPFChatExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="NetworkComms .Net WPF Chat Example" Height="341" Width="512" Background="#FF7CA0FF" ResizeMode="CanMinimize">
    <Grid>
//服务器IP
        <TextBox Height="23" HorizontalAlignment="Left" Margin="68,8,0,0" Name="serverIP" VerticalAlignment="Top" Width="97" />
        <Label Content="Server IP:" Height="28" HorizontalAlignment="Left" Margin="8,6,0,0" Name="label1" VerticalAlignment="Top" />

//端口
        <TextBox Height="23" HorizontalAlignment="Left" Margin="199,8,0,0" Name="serverPort" VerticalAlignment="Top" Width="47" />
        <Label Content="Port:" Height="28" HorizontalAlignment="Left" Margin="166,6,0,0" Name="label2" VerticalAlignment="Top" />
//一个TextBox 
        <TextBox Height="231" HorizontalAlignment="Left" Margin="11,38,0,0" Name="chatBox" VerticalAlignment="Top" Width="356" IsReadOnly="True" VerticalScrollBarVisibility="Visible" />
//Messages from:
        <Label Content="Messages from:" Height="28" HorizontalAlignment="Left" Margin="369,84,0,0" Name="label3" VerticalAlignment="Top" Width="98" />
        <TextBox Height="161" HorizontalAlignment="Left" Margin="373,108,0,0" Name="messagesFrom" VerticalAlignment="Top" Width="117" IsReadOnly="True" VerticalScrollBarVisibility="Auto" />

//Local Name
        <Label Content="Local Name:" Height="28" HorizontalAlignment="Left" Margin="293,7,0,0" Name="label4" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="373,8,0,0" Name="localName" VerticalAlignment="Top" Width="117" />
//Message:
        <Label Content="Message:" Height="28" HorizontalAlignment="Left" Margin="5,272,0,0" Name="label5" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="62,274,0,0" Name="messageText" VerticalAlignment="Top" Width="305" /
//Send
        <Button Content="Send" Height="23" HorizontalAlignment="Left" Margin="373,274,0,0" Name="sendMessageButton" VerticalAlignment="Top" Width="117"/>
//CheckBox Enable Server
        <CheckBox Content="Enable Server" Height="16" HorizontalAlignment="Left" Margin="377,44,0,0" x:Name="enableServer" VerticalAlignment="Top"/>
//CheckBox Use Encryption
        <CheckBox Content="Use Encryption" Height="16" HorizontalAlignment="Left" Margin="377,65,0,0" Name="useEncryptionBox" VerticalAlignment="Top"/>
    </Grid>
</Window>



 
4. Add ChatMessage Wrapper Class
•The next step is to create a wrapper class for the messages we will be sending and receiving, i.e. a single object we send and receive that contains all necessary information. Right click on the project and select ‘Add‘ > ‘New Item…‘. This should bring up the ‘Add New Item‘ window, a list of options that you can add to the project. Ensure that ‘Class‘ item is selected, and at the bottom of the window enter the name ‘ChatMessage.cs‘. Now click ‘Add‘. The new class file should open automatically and you should now have something like this:
译:
4、添加一个ChatMessage包类
    右击,“添加”>“新项...”,弹出“添加新项”窗口,确保“类”项被选中。类名字为“ChatMessage.cs”
•Copy and paste the following code, replacing ALL EXISTING code in the class we just created, ‘ChatMessage.cs‘:
译:
将下述代码全部替掉“ChatMessage.cs”里的原有代码。
           注: networkcomms.net2.3.1通信框架源码\MarcF-networkcomms.net2.3.1\ExamplesChat.WPF  与这个版本的代码差不多

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

//We need to include the following three namespaces to this class
using NetworkCommsDotNet;
using NetworkCommsDotNet.Tools;
using ProtoBuf;

namespace WPFChatExample
{
    /// <summary>
    /// A wrapper class for the messages that we intend to send and receive.
    /// The [ProtoContract] attribute informs NetworkComms .Net that we intend to
    /// serialise (turn into bytes) this object. At the base level the
    /// serialisation is performed by protobuf.net.
    /// </summary>
    [ProtoContract]
    class ChatMessage
    {
        /// <summary>
        /// The source identifier of this ChatMessage.
        /// We use this variable as the constructor for the ShortGuid.
        /// The [ProtoMember(1)] attribute informs the serialiser that when
        /// an object of type ChatMessage is serialised we want to include this variable
        /// </summary>
        [ProtoMember(1)]
        string _sourceIdentifier;

        /// <summary>
        /// The source identifier is accessible as a ShortGuid
        /// </summary>
        public ShortGuid SourceIdentifier { get { return new ShortGuid(_sourceIdentifier); } }

        /// <summary>
        /// The name of the source of this ChatMessage.
        /// We use shorthand declaration, get and set.
        /// The [ProtoMember(2)] attribute informs the serialiser that when
        /// an object of type ChatMessage is serialised we want to include this variable
        /// </summary>
        [ProtoMember(2)]
        public string SourceName { get; private set; }

        /// <summary>
        /// The actual message.
        /// </summary>
        [ProtoMember(3)]
        public string Message { get; private set; }

        /// <summary>
        /// The index of this message. Every message sent by a particular source
        /// has an incrementing index.
        /// </summary>
        [ProtoMember(4)]
        public long MessageIndex { get; private set; }

        /// <summary>
        /// The number of times this message has been relayed.
        /// </summary>
        [ProtoMember(5)]
        public int RelayCount { get; private set; }

        /// <summary>
        /// We must include a private constructor to be used by the deserialisation step.
        /// </summary>
        private ChatMessage() { }

        /// <summary>
        /// Create a new ChatMessage
        /// </summary>
        /// <param name="sourceIdentifier">The source identifier</param>
        /// <param name="sourceName">The source name</param>
        /// <param name="message">The message to be sent</param>
        /// <param name="messageIndex">The index of this message</param>
        public ChatMessage(ShortGuid sourceIdentifier, string sourceName, string message, long messageIndex)
        {
            this._sourceIdentifier = sourceIdentifier;  //注意这5句
            this.SourceName = sourceName;
            this.Message = message;
            this.MessageIndex = messageIndex;
            this.RelayCount = 0;
        }

        /// <summary>
        /// Increment the relay count variable
        /// </summary>
        public void IncrementRelayCount()
        {
            RelayCount++;
        }
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值