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

1.前提

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

2,代码部分

实现的效果,在点击开始监听后,打开监听端口后,然后可以打开客户端,打开客户端后,可以进行消息的发送,在监听端的代码可能没有处理好导致服务器端监听的消息会出现显示问题,由于时间问题,没有再去修改,服务器端的作用只要对消息进行发送,并不需要对消息进行显示,并不影响测试的效果。
服务器端代码--前台代码

    
        
        
服务器端代码--后台代码
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
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        
        // 创建一个和客户端通信的套接字
        static Socket serverSocket = null;
        static List sockets = new List();
        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();        

        }
           
    }
    
}
客户端代码--前台代码

    
        
        
客户端代码--后台代码
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
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    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();
          
        }
    }
}


 

你可能感兴趣的:(wpf,wpf)