Как прослушивать клиентом сервер - C#
Формулировка задачи:
Всем привет, столкнулся с проблемой, что клиент подключается к серверу передавая имя подключившегося пользователя. Но далее дело не заходит , не получается клиентом прослушивать отправления сервера и заполнять текстбокс(для чата) и не работает отправка на сервер.
Вот код клиента.
__________
Код сервера
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.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Game_Client_V._0._0._1
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Thread tUpdateChat;
string PlayerName;
string KeyAddPlayer = "Player: ";
public static Socket Client;
private IPEndPoint ipEndPoint;
private IPAddress IP_Server = null;
private int Port;
public MainWindow()
{
InitializeComponent();
TB_CHAT.Visibility = Visibility.Collapsed;
TB_CHAR_R.Visibility = Visibility.Collapsed;
B_SendMessage.Visibility = Visibility.Collapsed;
EL_INFO_COLOR_1.Visibility = Visibility.Collapsed;
B_EXIT.Visibility = Visibility.Collapsed;
try
{
var rd = new StreamReader("server_info.conf");
string Config = rd.ReadLine();
rd.Close();
string[] ConfigSplit = Config.Split(':');
IP_Server = IPAddress.Parse(ConfigSplit[0]);
Port = int.Parse(ConfigSplit[1]);
LB_INFO_CONNECTION.Foreground = Brushes.Green;
EL_INFO_COLOR.Stroke = Brushes.Green;
EL_INFO_COLOR.Fill = Brushes.Green;
LB_INFO_CONNECTION.Content = "Настройки успешно инициализированы \n" + "IP адрес сервера: " + ConfigSplit[0] + "\nПорт: " + ConfigSplit[1];
}
catch
{
EL_INFO_COLOR.Stroke = Brushes.Red;
EL_INFO_COLOR.Fill = Brushes.Red;
LB_INFO_CONNECTION.Foreground = Brushes.Red;
LB_INFO_CONNECTION.Content = "\nОшибка инициализации настроек";
B_CHANGE_CONFIG.Background = Brushes.Red;
}
}
private void RecvMessage()
{
byte[] Buffer = new byte[1024];
for (int i = 0; i < Buffer.Length; i++)
{
Buffer[i] = 0;
}
for (;;)
{
try
{
string Message;
int bytesRec = Client.Receive(Buffer);
Message = Encoding.UTF8.GetString(Buffer, 0, bytesRec);
TB_CHAR_R.Text = Message;
Thread.Sleep(1000);
}
catch
{
}
}
}
private void SendMessage (string Message)
{
if (Message != String.Empty && Message != " ")
{
byte[] ByteMessage = Encoding.UTF8.GetBytes(Message);
int bytesSent = Client.Send(ByteMessage);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Client = new Socket(IP_Server.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
ipEndPoint = new IPEndPoint(IP_Server, Port);
if (IP_Server != null)
{
Client.Connect(ipEndPoint);
PlayerName = TB_NAME.Text;
if (PlayerName == String.Empty)
{
MessageBox.Show("Введите имя пользователя");
}
else
{
EL_INFO_COLOR_1.Visibility = Visibility.Visible;
EL_INFO_COLOR_1.Stroke = Brushes.Green;
EL_INFO_COLOR_1.Fill = Brushes.Green;
LB_INFO.Content = "Соединение установлено";
LB_INFO.Foreground = Brushes.Green;
TB_NAME.Visibility = Visibility.Collapsed;
B_Connect.Visibility = Visibility.Collapsed;
TB_CHAT.Visibility = Visibility.Visible;
TB_CHAR_R.Visibility = Visibility.Visible;
B_SendMessage.Visibility = Visibility.Visible;
B_EXIT.Visibility = Visibility.Visible;
byte[] ByteMessage = Encoding.UTF8.GetBytes(KeyAddPlayer + PlayerName);
int bytesSent = Client.Send(ByteMessage);
tUpdateChat = new Thread(RecvMessage);
}
}
}
private void B_SendMessage_Click(object sender, RoutedEventArgs e)
{
SendMessage(PlayerName + ": " + TB_CHAT.Text + "\n");
TB_CHAT.Text = String.Empty;
}
private void B_EXIT_Click(object sender, RoutedEventArgs e)
{
tUpdateChat.Abort();
Environment.Exit(0);
}
}
}using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
namespace SocketServer
{
class Program
{
static void Main(string[] args)
{
List<string> Players = new List<string>();
int Count_Clients;
string KeyPlayer = "Player: ";
// Устанавливаем для сокета локальную конечную точку
//IPHostEntry ipHost = IPAddress.Parse("127.0.0.1")//Dns.GetHostEntry("localhost");
IPAddress ipAddr = IPAddress.Parse("127.0.0.1");//ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
// Создаем сокет Tcp/Ip
Socket sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Назначаем сокет локальной конечной точке и слушаем входящие сокеты
try
{
sListener.Bind(ipEndPoint);
sListener.Listen(10);
// Начинаем слушать соединения
while (true)
{
Console.WriteLine("Ожидаем соединение через порт {0} \n", ipEndPoint);
// Программа приостанавливается, ожидая входящее соединение
Socket handler = sListener.Accept();
string data = null;
Console.WriteLine("Запрос на подключение нового клиента выполнен! \n");
// Мы дождались клиента, пытающегося с нами соединиться
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
if (data.Contains(KeyPlayer))
Players.Add(data);
Count_Clients = Players.Count;
// Показываем данные на консоли
Console.Write("Полученный текст: " + data + Players.Count + "\n\n");
// Отправляем ответ клиенту\
string reply = "";
reply += data;
byte[] msg = Encoding.UTF8.GetBytes(reply);
handler.Send(msg);
if (data.IndexOf("<TheEnd>") > -1)
{
Console.WriteLine("Сервер завершил соединение с клиентом.");
break;
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
Console.ReadLine();
}
}
}
}Решение задачи: «Как прослушивать клиентом сервер»
textual
Листинг программы
private void SendMessage (string Message)
{
if (Message != String.Empty && Message != " ")
{
byte[] ByteMessage = Encoding.UTF8.GetBytes(Message);
int bytesSent = Client.Send(ByteMessage);
}
}