S
S
Stepan Gervik2019-01-10 15:47:52
C++ / C#
Stepan Gervik, 2019-01-10 15:47:52

How to make a C# server?

Hello! There is a code on C# application server-client.
Here is the server code:
class ClientObject

spoiler
public TcpClient client;
        public ClientObject(TcpClient tcpClient)
        {
            client = tcpClient;
        }

        public void Process()
        {
            NetworkStream stream = null;
            try
            {
                stream = client.GetStream();
                byte[] data = new byte[64]; // буфер для получаемых данных
                while (true)
                {
                    // получаем сообщение
                    StringBuilder builder = new StringBuilder();
                    int bytes = 0;
                    do
                    {
                        bytes = stream.Read(data, 0, data.Length);
                        builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                    }
                    while (stream.DataAvailable);

                    string message = builder.ToString();

                    Console.WriteLine(message);
                    Console.WriteLine("/");
                    // отправляем обратно сообщение в верхнем регистре
                    message = Console.ReadLine();
                    
                        data = Encoding.Unicode.GetBytes(message);
                    
                        stream.Write(data, 0, data.Length);
                    
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (stream != null)
                    stream.Close();
                if (client != null)
                    client.Close();
            }
        }

class Program
spoiler
const int port = 8888;
        static TcpListener listener;
        static void Main(string[] args)
        {
            try
            {
                listener = new TcpListener(port);
                listener.Start();
                Console.WriteLine("Ожидание подключений...");
                
                TcpClient client = listener.AcceptTcpClient();
                ClientObject clientObject = new ClientObject(client);
                Thread clientThread = new Thread(new ThreadStart(clientObject.Process));
                clientThread.Start();
            
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (listener != null)
                    listener.Stop();
            }
        }

And here is the client itself:
class Program
spoiler
const int port = 8888;
        const string address = "127.0.0.1";
        static void Main(string[] args)
        {
            Console.Write("Введите свое имя:");
            string userName = Console.ReadLine();
            TcpClient client = null;
            
                client = new TcpClient(address, port);
                NetworkStream stream = client.GetStream();

                while (true)
                {
                    Console.Write(userName + ": ");
                    // ввод сообщения
                    string message = Console.ReadLine();
                    message = String.Format("{0}: {1}", userName, message);
                    // преобразуем сообщение в массив байтов
                    byte[] data = Encoding.Unicode.GetBytes(message);
                    // отправка сообщения
                    stream.Write(data, 0, data.Length);
                    // получаем ответ
                    data = new byte[64]; // буфер для получаемых данных
                    StringBuilder builder = new StringBuilder();
                    int bytes = 0;
                    do
                    {
                        bytes = stream.Read(data, 0, data.Length);
                        builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                    }
                    while (stream.DataAvailable);

                    message = builder.ToString();
                    Console.WriteLine("Сервер: {0}", message);
                }
            
        }

The very essence of the problem ..
The fact is that when I connect to the server through a client, the server launches a thread for this connection .. When you start another client, another thread comes out, therefore, because of this, I cannot send to all clients the same message. That is, when I enter, it first goes to the first connected client, when I enter the second time, it rushes to the second, etc..
Please tell me how to solve such a problem

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2019-01-10
@petermzg

So don't create separate threads for each new client connection.
Save connections to an array and send data to all saved connections when needed.

R
RomarioSPb, 2019-01-15
@RomarioSPb

https://metanit.com/sharp/net/4.2.php - everything seems to be written in an accessible way, suddenly it will help.
You can alternatively use an asynchronous TcpListener and not bother with sockets

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question