.NET 3.x Уведомление клиента о смене IP адреса сервера - C#
Формулировка задачи:
IP Динамический передача клиенту от сервера
суть такая
Server
IP: 192.168.1.25 (локальный)
Port: 7890
Client
IP: 179.189.14.25 (внешний динамический)
Port: 7890
тут будет связь клиента с сервером через интернет
пока адресс внешний будет не меняться
как только IP(Внешний) измениться то клиент уже не сможет сойдениться с сервером
Я так понял клиент шлет серверу сообщение - а сервер отвечает на него
это как удочку закинуть , и на удочку чепляеться рыбка
если не закинуть то и рыбки не будет, в конкретном адресе пруда))
но если клиент слал первое сообщение , то сервер должен знать адресс клиента
и может отреагировав на изменения своего IP отослать клиенту
клиент приймет , и будет ловить рыбу уже у другом пруду ))
Вот и спрашиваю можно ли так сделать ))
вот мой Сервер
Клиент
подкинте пример на C# как это можно , или нельзя осушетвить
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Windows.Forms;
using WindowsFormsApplication_ip;
using download_link;
namespace Server
{
class Program
{
static Read_file readFile=new Read_file();
static GetAddressIP getAddressIp=new GetAddressIP();
static string[] read_file_ip_port()
{
string ip = String.Empty;
int port = 0, ip1 = 0, ip2 = 0, ip3 = 0, ip4 = 0;
string[] array=new string[2];
string[] lines = readFile.Get_file_line("ip_address.txt", Encoding.GetEncoding(1251));
try
{
lines = readFile.not_empty_array(lines);
string[] ipstr = lines[0].Split('.');
ip1 = Convert.ToInt32(ipstr[0]);
ip2 = Convert.ToInt32(ipstr[1]);
ip3 = Convert.ToInt32(ipstr[2]);
ip4 = Convert.ToInt32(ipstr[3]);
ip = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
port = Convert.ToInt32(lines[1]);
array[0] = ip;
array[1] = port.ToString();
}
catch (Exception ex)
{
Console.WriteLine("Ошибка: " + ex.Message);
Console.ReadKey(true);
Environment.Exit(0);
}
return array;
}
static void Main(string[] args)
{
form_consol("Сервер v 1.3");
string ip = String.Empty;
int port = 0,num=0;
Console.Write("Номер IP Сетевой Адаптера: ");
try
{
num = Convert.ToInt32(Console.ReadLine());
num = num - 1;
if (num<0)
{
Console.WriteLine("Ошибка номер IP не должен быть равен 0, или ниже нуля!");
num = 0;
}
}
catch (Exception ex)
{
Console.WriteLine("Введены символы, заместь номера IP :"+ex.Message);
}
ip = getAddressIp.Get_Local_IP(num);
port = Convert.ToInt32(read_file_ip_port()[1]);
if (ip!=String.Empty && port!=0)
{
Console.WriteLine("Локальный IP: "+ip+" | Порт: "+port+"\n");
//Сервер подключаеться к локальному своему IP ПК и порту 12000 что открыт через модем в инете
TcpListener listner = new TcpListener(new IPEndPoint(IPAddress.Parse(ip), port));
listner.Start();
try
{
while (true)
{
string messag = String.Empty;
TcpClient client = listner.AcceptTcpClient();
StreamReader sr = new StreamReader(client.GetStream());
Console.WriteLine("Клиент : " + sr.ReadLine());
StreamWriter sw = new StreamWriter(client.GetStream());
sw.AutoFlush = true;
Console.Write("Server : ");
messag = Console.ReadLine();
sw.WriteLine(messag);
while (true)
{
Console.WriteLine("Клиент : " + sr.ReadLine());
Console.Write("Server : ");
messag = Console.ReadLine();
sw.WriteLine(messag);
}
//sw.WriteLine("Пока");
//client.Close();
}
}
catch
(Exception ex)
{
Console.WriteLine("Ошибка: " + ex.Message);
Console.ReadKey(true);
Environment.Exit(0);
}
}
}
static void form_consol(string title)
{
Console.BackgroundColor = ConsoleColor.DarkCyan;
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
Console.Title = title;
}
}
}using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using download_link;
namespace Client
{
class Program
{
static Read_file readFile = new Read_file();
static string[] read_file_ip_port(string fileread)
{
string ip = String.Empty;
int port = 0, ip1 = 0, ip2 = 0, ip3 = 0, ip4 = 0;
string[] array = new string[2];
string[] lines = readFile.Get_file_line(fileread, Encoding.GetEncoding(1251));
try
{
lines = readFile.not_empty_array(lines);
string[] ipstr = lines[0].Split('.');
ip1 = Convert.ToInt32(ipstr[0]);
ip2 = Convert.ToInt32(ipstr[1]);
ip3 = Convert.ToInt32(ipstr[2]);
ip4 = Convert.ToInt32(ipstr[3]);
ip = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
port = Convert.ToInt32(lines[1]);
array[0] = ip;
array[1] = port.ToString();
}
catch (Exception ex)
{
Console.WriteLine("Ошибка: " + ex.Message);
Console.ReadKey(true);
Environment.Exit(0);
}
return array;
}
static void Main(string[] args)
{
form_consol("Клиент v 1.3");
string fileaddress = "address.pr";
try
{
string ip=String.Empty;
int port = 0,ip1=0,ip2=0,ip3=0,ip4=0;
ip = read_file_ip_port(fileaddress)[0];
port = Convert.ToInt32(read_file_ip_port(fileaddress)[1]);
if (File.Exists(fileaddress) ==false)
{
Console.Write("Введите IP: ");
ip1 = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.Write("Введите IP: " + ip1+".");
ip2 = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.Write("Введите IP: " + ip1 + "."+ip2+".");
ip3 = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.Write("Введите IP: " + ip1 + "."+ip2+"."+ip3+".");
ip4 = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.Write("Введите IP: " + ip1 + "."+ip2+"."+ip3+"."+ip4+"\n");
ip = ip1 + "."+ip2+"."+ip3+"."+ip4;
Console.WriteLine("\n\nСойдинение по IP: "+ip);
Console.Write("\n\nВведите Порт: ");
port = Convert.ToInt32(Console.ReadLine());
}
if (ip!=String.Empty && port!=0)
{
Console.Clear();
TcpClient client = new TcpClient();
Console.WriteLine("Подождите идет сойдинение....");
//Клиент подключаеться к внешнему IP и открытому порту 12000 в инете
//Console.WriteLine(ip);
client.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
Console.Clear();
while (true)
{
string mssage = String.Empty;
StreamWriter sw = new StreamWriter(client.GetStream());
sw.AutoFlush = true;
Console.Write("Клиент : ");
//sw.WriteLine("Привет");
mssage = Console.ReadLine();
sw.WriteLine(mssage);
StreamReader sr = new StreamReader(client.GetStream());
Console.WriteLine("Server : " + sr.ReadLine());
while (true)
{
Console.Write("Клиент : ");
mssage = Console.ReadLine();
sw.WriteLine(mssage);
//sw.WriteLine("Пока");
Console.WriteLine("Server : " + sr.ReadLine());
}
//client.Close();
//Console.ReadKey();
}
}
else
{
Console.Clear();
Console.WriteLine("Данные IP и Port , не могут быть пусты!");
}
}
catch (Exception ex)
{
Console.Clear();
Console.WriteLine("Ошибка: "+ex.Message);
Console.ReadKey(true);
Environment.Exit(0);
}
}
static void form_consol(string title)
{
Console.BackgroundColor=ConsoleColor.DarkCyan;
Console.Clear();
Console.ForegroundColor=ConsoleColor.White;
Console.Title = title;
}
}
}Решение задачи: «.NET 3.x Уведомление клиента о смене IP адреса сервера»
textual
Листинг программы
IPHostEntry ipHost = Dns.GetHostEntry(rsa.decode("chat.example.com");
IPAddress ip = ipHost.AddressList[0];
//плевать как будет меняться внешний ip, его можно всегда получить хостом
//ip вяжем к клиенту и так далее..