Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/4: Рейтинг темы: голосов - 4, средняя оценка - 5.00
Труд вопреки насмешкам
288 / 165 / 40
Регистрация: 13.07.2017
Сообщений: 3,000
Записей в блоге: 8
1

Клиент-сервер. Не удается подключить второго клиента

11.09.2019, 20:21. Показов 747. Ответов 1
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Код сервера:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
    class Program
    {
        // Incoming data from the client.
        private static string data = "";
        private static List<string> clients = new List<string>();
 
        private static void StartListening()
        {
            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];
 
            // Establish the local endpoint for the socket.
            IPHostEntry ip_host_info = Dns.GetHostEntry("localhost");
            IPAddress ip_address = ip_host_info.AddressList[0];
            IPEndPoint local_end_point = new IPEndPoint(ip_address, 11000);
 
            // Create a TCP/IP socket.
            Socket listener = new Socket(ip_address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  
            // Bind the socket to the local endpoint and   
            // listen for incoming connections.  
            try
            {
                listener.Bind(local_end_point);
                listener.Listen(64);
 
                // Start listening for connections.
                while (true)
                {
                    Socket handler = Accept(bytes, listener);
 
                    // Show the data on the console.
                    Console.WriteLine(data = data.Replace("<EOF>", ""));
                    if (data.StartsWith("Пытается подключиться ") == true)
                    {
                        ConnectNew();
                    }
                    else
                    {
                        Console.WriteLine("Сервер: Сообщение принято: " + data);
                    }
                    if (data.EndsWith(": Пока!") == true)
                    {
                        clients.Remove(data.Substring(0, data.IndexOf(": Пока!")));
                    }
 
                    // Echo the data back to the client.
                    byte[] msg = Encoding.Default.GetBytes(data);
 
                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception ex)
            {  
                Console.WriteLine("Ошибка: " + ex.ToString());  
            }  
 
            Console.WriteLine("\nPress any key to continue...");  
            Console.ReadKey(true);  
        }
 
        private static Socket Accept(byte[] bytes, Socket listener)
        {
            Console.WriteLine("Waiting for a connection...");
            // Program is suspended while waiting for an incoming connection.
            Socket handler = listener.Accept();
            data = "";
 
            // An incoming connection needs to be processed.
            while (true)
            {
                int bytes_rec = handler.Receive(bytes);
                data += Encoding.Default.GetString(bytes, 0, bytes_rec);
                if (data.LastIndexOf("<EOF>") != -1)
                {
                    break;
                }
            }
 
            return handler;
        }
 
        private static void ConnectNew()
        {
            string new_name = data.Replace("Пытается подключиться ", "");
            if (clients.Contains(new_name) == true)
            {
                Console.WriteLine("Ошибка, это имя уже зарегистрировано!");
            }
            else
            {
                Console.WriteLine("Сервер: " + "Привет, " + new_name + "!");
                clients.Add(new_name);
            }
        }
 
        static void Main()
        {
            StartListening();
        }
    }
Код клиента:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
    class Program
    {
        private static string name = "";
 
        private static void StartClient()
        {
            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];
 
            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // This example uses port 11000 on the local computer.
                IPHostEntry ip_host_info = Dns.GetHostEntry("localhost");
                IPAddress ip_address = ip_host_info.AddressList[0];
                IPEndPoint remote_end_point = new IPEndPoint(ip_address, 11000);
 
                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    // Create a TCP/IPsocket.
                    Socket name_sender = new Socket(ip_address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
 
                    Send(remote_end_point, name_sender);
 
                    // Receive the response from the remote device.
                    int name_bytes_rec = name_sender.Receive(bytes); //Тут
                    name = Encoding.Default.GetString(bytes, 0, name_bytes_rec).Replace("Пытается подключиться ", "").Replace("<EOF>", "");
                    Console.WriteLine("Имя послано: {0}", name);
 
                    // Release the socket.
                    name_sender.Shutdown(SocketShutdown.Both);
                    name_sender.Close();
                    while (true)
                    {
                        // Create a TCP/IPsocket.
                        Socket sender = new Socket(ip_address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
 
                        Send(remote_end_point, sender);
 
                        // Receive the response from the remote device.
                        int bytes_rec = sender.Receive(bytes);
                        string data = Encoding.Default.GetString(bytes, 0, bytes_rec).Replace("<EOF>", "");
                        Console.WriteLine("Вопрос послан: {0}", data);
                        if (data == "Пока!")
                        {
                            break;
                        }
 
                        // Release the socket.
                        sender.Shutdown(SocketShutdown.Both);
                        sender.Close();
                    }
                }
                catch (ArgumentNullException an_ex)
                {
                    Console.WriteLine("Ошибка ArgumentNullException: {0}", an_ex.ToString());
                }
                catch (SocketException s_ex)
                {
                    Console.WriteLine("Ошибка SocketException: {0}", s_ex.ToString());
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Ошибка: {0}", ex.ToString());
                }
 
            }
            catch (Exception ex)
            {
                Console.WriteLine("Ошибка: {0}", ex.ToString());
            }
 
            Console.WriteLine("\nPress any key to continue...");  
            Console.ReadKey(true);  
        }
 
        private static void Send(IPEndPoint remote_end_point, Socket sender)
        {
            sender.Connect(remote_end_point);
 
            Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
 
            // Encode the data string into a byte array.
            byte[] msg = Encoding.Default.GetBytes(((name == "") ? "Пытается подключиться " : name + ": ") + Console.ReadLine() + "<EOF>");
 
            // Send the data through the socket.
            sender.Send(msg);
        }
 
        static void Main()
        {
            Console.WriteLine("Напишите сообщение, и сервер примет его.");
            Console.WriteLine("На сообщении \"Пока!\" соединение закрывается.");
            Console.WriteLine("ПЕРВЫМ сообщением должно быть ваше имя!");
            StartClient();
        }
    }
С одним клиентом все в порядке. Но как только ВТОРОЙ клиент доходит до места, отмеченного "Тут", он зависает! Кто знает, в чем может быть причина?

Добавлено через 1 минуту
Надеюсь, этот код можно понять?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
11.09.2019, 20:21
Ответы с готовыми решениями:

Как отправить json с клиента на сервер (клиент - прога на C#, сервер - файл PHP)
На хостинге есть файл php, как мне отправить к этому файлу json c помощью C# и как получить его с...

Клиент-сервер, передать строку с клиента на сервер
Подскажите плиз Есть код он передает серверу то что мы пишем с клавиатуры а как передать строку...

Клиент-Сервер. Распознавание клиента
День добрый. Подскажите пожалуйста, как сделать так, чтобы при подключении к серверу не одного, а...

Чат "Сервер-клиент". На сервер не могу отправить сообщение с клиента
Не могу понять как сделать, чтоб сервер ещё прослушивал и сообщения... Нет ли входящих данных....

1
18 / 16 / 8
Регистрация: 27.05.2017
Сообщений: 118
12.09.2019, 14:13 2
Твой код вполне понятный, и работает как надо у меня(проверял в 15 студии)...
Я тоже интересовался этой темой, и есть у меня наработки. Попробуешь может мой код подойдет...
Вот мой вариант код сервера:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
 
namespace ConsoleChat1_Server
{
    class Program
    {
        static TcpListener tcpListener; //монитор подключений TCP клиентов
        static Thread listenThread; //создание потока
 
        static List<TcpClient> clients = new List<TcpClient>(); //список клиентских подключений
        static List<NetworkStream> netStream = new List<NetworkStream>(); //список потока данных
 
        static void Main(string[] args)
        {
 
            try
            {
                Console.WriteLine("Server Started!");
                tcpListener = new TcpListener(IPAddress.Any, 8888);
                listenThread = new Thread(new ThreadStart(ListenThread));
                listenThread.Start(); //старт потока
            }
            catch
            {
                Disconnect();
            }
        }
 
        static void ListenThread()
        {
            tcpListener.Start();
 
            while (true)
            {
                clients.Add(tcpListener.AcceptTcpClient()); //подключение пользователя
                netStream.Add(clients[clients.Count - 1].GetStream()); //обьект для получения данных
 
                Thread clientThread = new Thread(new ParameterizedThreadStart(ClientRecieve));
                clientThread.Start(clients.Count - 1);
            }
        }
 
        static void ClientRecieve(object ID)
        {
            int thisID = (int)ID;
 
            byte[] recieve = new byte[64];
 
            while (true)
            {
                try
                {
                    netStream[thisID].Read(recieve, 0, 64);
 
                    Console.WriteLine(Encoding.UTF8.GetString(recieve));
                    SendMessageToClients(recieve);
                    for (int i = 0; i < 64; i++)
                    {
                        recieve[i] = 0;
                    }
                }
                catch
                {
                    Console.WriteLine("Client with ID: " + thisID + " has Disconnected!");
                    break;
                }
            }
        }
 
        static void SendMessageToClients(byte[] toSend)
        {
            for (int i = 0; i < netStream.Count; i++)
            {
                netStream[i].Write(toSend, 0, 64); //передача данных
                netStream[i].Flush(); //удаление данных с потока
            }
        }
 
        static void Disconnect()
        {
            tcpListener.Stop(); //остановка чтения
 
            for (int i = 0; i < clients.Count; i++)
            {
                clients[i].Close(); //отключение клиента
                netStream[i].Close(); //отключение потока
            }
            Environment.Exit(0); //завершение процесса
        }
    }
}
и конечно код клиента:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
 
namespace ConsoleChat1_Client
{
    class Program
    {
        static string usr;
        static TcpClient client;
        static NetworkStream netStream;
 
        static void Main(string[] args)
        {
            Console.Write("User name: ");
            usr = Console.ReadLine();
            Console.Write("IP: ");
            string ip = Console.ReadLine();
            Console.Write("Port: ");
            int port = Convert.ToInt32(Console.ReadLine());
            Connect(ip, port);
        }
 
        static void Connect(string ip, int port)
        {
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), port); //IP с номером порта
            client = new TcpClient(); //подключение клиента
            try
            {
                client.Connect(ipe); 
                netStream = client.GetStream();
                Thread receiveThread = new Thread(new ParameterizedThreadStart(ReceiveData));//получение данных
                receiveThread.Start();//старт потока
                Console.WriteLine("Connected!");
 
            }
            catch
            {
                Connect(ip, port);
            }
            SendMessage();
        }
 
        static void SendMessage()
        {
            Console.Write("Message: ");
            while (true)
            {
                try
                {
                    string message = usr + ": " + Console.ReadLine();
                    byte[] toSend = new byte[64];
                    toSend = Encoding.UTF8.GetBytes(message);
                    netStream.Write(toSend, 0, toSend.Length);
                    netStream.Flush(); //удаление данных из потока
                    //Console.WriteLine(message);
                    for (int i = 0; i < message.Length; i++)
                    {
                        toSend[i] = 0;
                    }
                }
                catch
                {
                    Console.WriteLine("ERROR");
                }
            }
        }
 
        static void ReceiveData(object e)
        {
            byte[] receiveMessage = new byte[64];
 
            while (true)
            {
                try
                {
                    netStream.Read(receiveMessage, 0, 64);//чтение сообщения
                }
                catch
                {
                    Console.WriteLine("The connection to the server was interrupted!"); //соединение было прервано
                    Console.ReadLine();
                    Disconnect();
                }
 
                string message = Encoding.UTF8.GetString(receiveMessage);
                Console.WriteLine(message);//вывод сообщения
            }
        }
 
 
        static void Disconnect()
        {
            client.Close();//отключение клиента
            netStream.Close();//отключение потока
            Environment.Exit(0); //завершение процесса
        }
    }
}
Я правда второго клиента не подключал, самому интересно будет ли так работать...
0
12.09.2019, 14:13
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
12.09.2019, 14:13
Помогаю со студенческими работами здесь

Клиент-сервер: регистрация клиента, администраторский доступ
Здравствуйте! Мне нужно сделать серверное применение программы на java, которое имеет админский и...

UDP клиент-сервер. Проброс порта у клиента
В TCP-IP т.к устанавливается соединение мы используем для связи с сервером тот же сокет с которым...

Клиент - сервер на UDP. странное поведение клиента
Добрый день ! среда Sharp developer , проект NET FW 4.0, Winforms делаю одну вещь : на...

Получить ip адрес клиента (асинхронный клиент - сервер)
Не могу получить ip адрес клиента (асинхронный клиент - сервер) при получении сообщения на стороне...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru