C#,WPF应用程序,许多tcpclients连接tcplistener(服务器)

时间:2017-04-25 09:46:08

标签: c# wpf tcpclient tcplistener networkstream

TcpServer.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Server
{
    public class TcpServer
    {
        static ServerGUI serverGUI;

        private const Int32 PORT = 13000;

        private const String ADDRESS = "127.0.0.1";

        private IPAddress localAddress;

        public TcpListener tcpServer;

        private static Byte[] bytes;

        private static String data;

        static DateTime localDate;
        static String cultureName = "de-DE";
        static CultureInfo cultureInfo;

        private static int clientCount = 0;

        private const char SEPERATOR = '|';

        static NetworkStream stream;

        public TcpServer()
        {
            serverGUI = new ServerGUI();
            serverGUI.Show();

            cultureInfo = new CultureInfo(cultureName);

            BackgroundWorker worker1 = new BackgroundWorker();
            worker1.DoWork += new DoWorkEventHandler(Worker1_DoWork);
            worker1.RunWorkerAsync();
        }

        private void Worker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)(async delegate ()
                {
                    localAddress = IPAddress.Parse(ADDRESS);
                    tcpServer = new TcpListener(localAddress, PORT);
                    localDate = DateTime.Now;
                    serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") chatserver has started.\n");
                    tcpServer.Start();
                    while (true)
                    {
                        TcpClient client = await tcpServer.AcceptTcpClientAsync();
                        ThreadPool.QueueUserWorkItem(ThreadProc, client);
                    }

                }));
            }
            catch (SocketException socketEx)
            {
                serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(delegate ()
                {
                    serverGUI.AddOutput(socketEx.Message + "\n");
                }));
            }
            catch (Exception ex)
            {
                serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(delegate ()
                {
                    serverGUI.AddOutput(ex.Message + "\n");
                }));
            }
            finally
            {
                if (tcpServer != null)
                {
                    tcpServer.Stop();
                }
            }
        }
        private static async void ThreadProc(object obj)
        {
            await serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(async delegate ()
             {
                 var client = (TcpClient)obj;
                 bytes = new Byte[256];
                 data = null;
                 // Get a stream object for reading and writing
                 stream = client.GetStream();

                 int i = 0;

                 while (true)
                 {
                     if (stream.CanRead)
                     {
                         i = await stream.ReadAsync(bytes, 0, bytes.Length);
                     }
                     localDate = DateTime.Now;

                     data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                     string[] receivedStr = data.Split(SEPERATOR);
                     byte[] msg = null;
                     if (receivedStr != null && receivedStr[0] == "new")
                     {
                         clientCount++;

                         msg = System.Text.Encoding.ASCII.GetBytes("chatserver" + SEPERATOR + "Welcome, " + receivedStr[2] + "! - active users: " + clientCount);

                         if (stream.CanWrite)
                         {
                             await stream.WriteAsync(msg, 0, msg.Length);
                         }


                         serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") new client recognized!\n");
                         serverGUI.AddOutput("                   " + receivedStr[1] + " - Nickname: " + receivedStr[2] + "\n");
                         serverGUI.AddOutput("                   " + "active clients: " + clientCount + "\n\n");
                     }
                     else if (receivedStr != null && receivedStr[0] == "close")
                     {
                         clientCount--;

                         msg = System.Text.Encoding.ASCII.GetBytes("chatserver" + SEPERATOR + "Goodbye, " + receivedStr[2] + "! - active users: " + clientCount);

                         if (stream.CanWrite)
                         {
                             await stream.WriteAsync(msg, 0, msg.Length);
                         }

                         serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") client disconnected!\n");
                         serverGUI.AddOutput("                   " + receivedStr[1] + " - Nickname: " + receivedStr[2] + "\n");
                         serverGUI.AddOutput("                   " + "active clients: " + clientCount + "\n\n");

                         client.Close();
                         break;
                     }
                     else
                     {

                         msg = System.Text.Encoding.ASCII.GetBytes(data);

                         if (stream.CanWrite)
                         {
                             await stream.WriteAsync(msg, 0, msg.Length);
                         }
                     }
                 }
             }));
        }
    }
}

(客户端)MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
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;

namespace Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Int32 port = 13000;

        private String hostname = "127.0.0.1";

        public TcpClient tcpClient;

        DateTime localDate;
        String cultureName = "de-DE";
        CultureInfo cultureInfo;

        BackgroundWorker worker1;
        NetworkStream stream;
        bool work = false;

        private const char SEPERATOR = '|';

        public MainWindow()
        {
            InitializeComponent();
            buttonDisconnect.IsEnabled = false;
            textBoxServerIP.Text = "127.0.0.1:13000";
            textBoxNickname.Text = "User";

            cultureInfo = new CultureInfo(cultureName);

            worker1 = new BackgroundWorker();
            worker1.DoWork += Worker1_DoWork;
        }

        private void Worker1_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)(async delegate ()
            {
                try
                {
                    while (work)
                    {

                        Byte[] data = System.Text.Encoding.ASCII.GetBytes("Hallo");

                        data = new Byte[256];

                        // String to store the response ASCII representation.
                        String responseData = String.Empty;

                        // Read the first batch of the TcpServer response bytes.
                        Int32 bytes = 0;
                        if (stream.CanRead)
                        {
                            bytes = await stream.ReadAsync(data, 0, data.Length);
                        }


                        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                        string[] receivedStr = responseData.Split(SEPERATOR);

                        if (receivedStr != null && receivedStr[0] == "chatserver")
                        {
                            textBoxChatRoom.Text += receivedStr[0] + " (" + localDate.ToString("g", cultureInfo) + "): " + receivedStr[1] + "\n\n";
                        }
                        else if (receivedStr != null && receivedStr[0] == "msg")
                        {
                            textBoxChatRoom.Text += receivedStr[1] + " (" + localDate.ToString("g", cultureInfo) + "): " + receivedStr[2] + "\n";
                        }
                        else
                        {
                            textBoxChatRoom.Text += responseData + "\n\n";
                        }
                    }

                }
                catch (ArgumentNullException argumentNullEx)
                {
                    textBoxChatRoom.Text += argumentNullEx.Message + "\n";
                }
                catch (SocketException socketEx)
                {
                    textBoxChatRoom.Text += socketEx.Message + "\n";
                }
                catch (InvalidOperationException invalidOperationEx)
                {
                    textBoxChatRoom.Text += invalidOperationEx.Message + "\n";
                }
                catch (Exception ex)
                {
                    textBoxChatRoom.Text += ex.Message + "\n";
                }
            }));

        }

        private async void buttonConnect_Click(object sender, RoutedEventArgs e)
        {

            string[] connectionStr = { "" };
            if (!textBoxServerIP.Text.Equals(null) && textBoxServerIP.Text != "")
            {
                connectionStr = textBoxServerIP.Text.Split(':');

                try
                {
                    hostname = connectionStr[0];
                    port = Int32.Parse(connectionStr[1]);
                    tcpClient = new TcpClient(connectionStr[0], Int32.Parse(connectionStr[1]));

                    //localDate = DateTime.Now;
                    textBoxChatRoom.Text += "Connecting to server " + connectionStr[0] + "...\n";
                    if (tcpClient.Connected)
                    {
                        textBoxChatRoom.Text += "Connected!\n";
                        textBoxServerIP.IsEnabled = false;
                        textBoxNickname.IsEnabled = false;
                        buttonConnect.IsEnabled = false;
                        buttonDisconnect.IsEnabled = true;
                        localDate = DateTime.Now;

                        stream = tcpClient.GetStream();

                        // Send the message to the connected TcpServer. 
                        byte[] msg = System.Text.Encoding.ASCII.GetBytes("new" + SEPERATOR + textBoxServerIP.Text.ToString() + SEPERATOR + textBoxNickname.Text.ToString());
                        if (stream.CanWrite)
                        {
                            await stream.WriteAsync(msg, 0, msg.Length);
                        }

                        work = true;
                        worker1.RunWorkerAsync();
                    }
                    else
                    {
                        textBoxChatRoom.Text += "not connected!\n";
                    }
                }
                catch (ArgumentNullException argumentNullExceptionEx)
                {
                    textBoxChatRoom.Text += argumentNullExceptionEx.Message + "\n";
                }
                catch (ArgumentOutOfRangeException argumentOutOfRangeEx)
                {
                    textBoxChatRoom.Text += argumentOutOfRangeEx.Message + "\n";
                }
                catch (SocketException socketEx)
                {
                    textBoxChatRoom.Text += socketEx.Message + "\n";
                }
                catch (FormatException formatEx)
                {
                    textBoxChatRoom.Text += formatEx.Message + "\n";
                }
                catch (OverflowException overflowEx)
                {
                    textBoxChatRoom.Text += overflowEx.Message + "\n";
                }
                catch (CultureNotFoundException cultureNotFoundEx)
                {
                    textBoxChatRoom.Text += cultureNotFoundEx.Message + "\n";
                }
                catch (Exception ex)
                {
                    textBoxChatRoom.Text += ex.Message + "\n";
                }
            }
            else
            {
                textBoxChatRoom.Text += "Please enter serverip!\n";
            }
        }


        private async void buttonDisconnect_Click(object sender, RoutedEventArgs e)
        {
            work = false;
            buttonConnect.IsEnabled = true;
            textBoxServerIP.IsEnabled = true;
            textBoxNickname.IsEnabled = true;
            buttonDisconnect.IsEnabled = false;

            byte[] msg = System.Text.Encoding.ASCII.GetBytes("close" + SEPERATOR + textBoxServerIP.Text.ToString() + SEPERATOR + textBoxNickname.Text.ToString());
            if (stream.CanWrite)
            {
                await stream.WriteAsync(msg, 0, msg.Length);
            }

        }

        private void buttonExit_Click(object sender, RoutedEventArgs e)
        {
            Environment.Exit(0);
        }

        private async void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Send the message to the connected TcpServer. 
                byte[] msg = System.Text.Encoding.ASCII.GetBytes("msg" + SEPERATOR + textBoxNickname.Text.ToString() + SEPERATOR + textBoxSend.Text);
                stream = tcpClient.GetStream();
                if (stream.CanWrite)
                {
                    await stream.WriteAsync(msg, 0, msg.Length);
                }

            }
            catch (ArgumentNullException argumentNullEx)
            {
                textBoxChatRoom.Text += argumentNullEx.Message + "\n";
            }
            catch (SocketException socketEx)
            {
                textBoxChatRoom.Text += socketEx.Message + "\n";
            }
            catch (InvalidOperationException invalidOperationEx)
            {
                textBoxChatRoom.Text += invalidOperationEx.Message + "\n";
            }
            catch (Exception ex)
            {
                textBoxChatRoom.Text += ex.Message + "\n";
            }
        }
    }
}

服务器和客户端之间的连接功能,但如果我使用一个客户端向网络流发送内容,则其他客户端不会收到任何内容。这应该是一个小聊天室-WPF应用程序 我有一个问题,我无法接收和发送多个客户端,我不知道我做错了什么... 请有人帮忙......

0 个答案:

没有答案