Труд вопреки насмешкам
288 / 165 / 40
Регистрация: 13.07.2017
Сообщений: 3,000
|
|
1
|
Клиент-сервер. Не удается подключить второго клиента
11.09.2019, 20:21. Показов 747. Ответов 1
Код сервера:
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
|