WPF使用socket实现多人聊天功能

1.前提

思路:一个服务器,多个客户端,每当客户端向服务器发送消息,服务器就会把当前客户端发送的信息发送给所有客户端,这里使用把所有的客户端放在一个集合中,每次接收到消息就会对所有的客户端发送消息,以便于能够实现多人聊天功能。关于socket的基础网上很多,就不再多说,直接看效果,

2,代码部分

实现的效果,在点击开始监听后,打开监听端口后,然后可以打开客户端,打开客户端后,可以进行消息的发送,在监听端的代码可能没有处理好导致服务器端监听的消息会出现显示问题,由于时间问题,没有再去修改,服务器端的作用只要对消息进行发送,并不需要对消息进行显示,并不影响测试的效果。
服务器端代码--前台代码
<Window x:Class="Server.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" >
    <Grid>
        <TextBox Name="text1" HorizontalAlignment="Left" Height="86" Margin="108,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>
        <Button Content="开始监听" HorizontalAlignment="Left" Margin="378,69,0,0" VerticalAlignment="Top" Width="75" Height="53" Click="Button_Click"/>

    </Grid>
</Window>
服务器端代码--后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 System.Net.Sockets;
using System.Net;
using System.Threading;
namespace Server
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        
        // 创建一个和客户端通信的套接字
        static Socket serverSocket = null;
        static List<Socket> sockets = new List<Socket>();
        public MainWindow()
        {
            InitializeComponent();         
        }      

        //监听客户端发来的请求  
        public void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                sockets.Add(clientSocket);                
                //为接受数据创建一个线程
                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientSocket);
            }  
        }
        public void ReceiveMessage(object clientSocket)
        {
            Socket connection = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    byte[] result = new byte[1024];  
                    //通过clientSocket接收数据  
                    int receiveNumber = connection.Receive(result);
                    //把接受的数据从字节类型转化为字符类型
                    String recStr = Encoding.ASCII.GetString(result, 0, receiveNumber);

                   
                    //获取当前客户端的ip地址
                    IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
                    //获取客户端端口
                    int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;
                    String sendStr = clientIP + ":" + clientPort.ToString() + "--->" + recStr;
                     foreach (Socket socket in sockets)
                    {
                        socket.Send(Encoding.ASCII.GetBytes(sendStr));
                    }
                    //显示内容
                     text1.Dispatcher.BeginInvoke(

                             new Action(() => { text1.Text += "\r\n" + sendStr; }), null);
                   
                }
                catch (Exception ex)
                {
                   
                    connection.Shutdown(SocketShutdown.Both);
                    connection.Close();
                    break;
                }
            }  
            
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, 6002));  //绑定IP地址:端口  
            serverSocket.Listen(10);    //设定最多10个排队连接请求             
            //通过Clientsoket发送数据  
            Thread myThread = new Thread(ListenClientConnect);
            myThread.Start();        

        }
           
    }
    
}
客户端代码--前台代码
<Window x:Class="Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Name="text1" HorizontalAlignment="Left" Height="46" Margin="96,156,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="124" />
        <Button Content="发送" HorizontalAlignment="Left" Height="45" Margin="286,156,0,0" VerticalAlignment="Top" Width="84" Click="Button_Click"/>
        <TextBox Name="text2" HorizontalAlignment="Left" Height="86" Margin="108,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="240"/>

    </Grid>
</Window>
客户端代码--后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 System.Net.Sockets;
using System.Net;
using System.Threading;
namespace Client
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
             String text = text1.Text;
            //设定服务器IP地址  
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientSocket.Connect(new IPEndPoint(ip, 6002));
            Thread receiveThread = new Thread(ReceiveMessage);
            receiveThread.Start(clientSocket);
        }

        public void ReceiveMessage(object clientSocket)
        {
            Socket connection = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //接受数据
                    byte[] result = new byte[1024];
                    //通过clientSocket接收数据  
                    int receiveNumber = connection.Receive(result);
                    //把接受的数据从字节类型转化为字符类型
                    String recStr = Encoding.ASCII.GetString(result, 0, receiveNumber);
                    text2.Dispatcher.BeginInvoke(

                           new Action(() => { text2.Text += "\r\n" + recStr; }), null);

                }
                catch (Exception ex)
                {

                    connection.Shutdown(SocketShutdown.Both);
                    connection.Close();
                    break;
                }
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            String text = text1.Text;
            //设定服务器IP地址  
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 6002)); //配置服务器IP与端口  
               
            }
            catch
            {
                Console.WriteLine("连接服务器失败,请按回车键退出!");
                return;
            }
            clientSocket.Send(Encoding.ASCII.GetBytes(text));

           

            //通过 clientSocket 发送数据  
            
            //clientSocket.Close();
          
        }
    }
}


 
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
WCF & WPF 聊天程序源码For those that have read some of my other CodeProject articles you will probably know, that I am not shy about trying out new technologies. But one good thing about that is that I generally share what I learn right here, and this article is one of the hardest ones I've done IMHO. This article is about how to create a peer-to-peer chat application using Windows Communication Foundation (WCF) and also how to make it look nice using Windows Presentation Foundation (WPF).When I first started reading about WCF, the first place I looked was the MSDN WCF Samples (which I read a lot), but they weren't that great. I also found lots of chat apps based on the MSDN versions, which were no good as they could not return the list of users within the chat application. So I wanted to create a nice WPF styled app with the list of connected chatters. So I hunted around a bit more and eventually came across a damn fine/brilliant article by Nikola Paljetak, which I have tailored for this article. I have OK'd this with Nikola, and the original article content is here. To be honest the original article was pure brilliance (it should be mentioned Nikola is a Professor), but it took a while for me to get what was going on, as the code wasn't commented. I have now commented all code, so I think it will still make a very nice discussion/article for those that are new to WCF/WPF. I was totally new to WCF before this article, so if I can do it, so can all of you.So that's what this article is all about. At the end of the article, I would hope you understand at least some of the key WCF areas, and possibly be inspired enough to look at the WPF side of this article also.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值