Получение ip-адреса для сервера - C#
Формулировка задачи:
Здравствуйте. Пробую разобраться с сервером на c# сидя на mac с xamarin studio.
При запуске проги идет попытка запустить сервер, но прога крашится из-за невозможности получения ip(не знаю почему). Хотя на винде все работает. Ругается на это Как исправить эту проблему?
КЛАСС Program.cs
КЛАСС Server.cs
P.S. Прога не моя, отсюда взял https://www.youtube.com/watch?v=-xtGcZkG1V4
System.Net.IPAddress ip = System.Net.Dns.GetHostByName(host).AddressList[0];
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace app
{
class Program
{
const int PORT = 90;
static void Main(string[] args)
{
Console.WriteLine("Запустить сервер? Y | N");
if (Console.ReadLine().Trim().ToUpper() == "Y")
{
//получение имени компъютера
string host = System.Net.Dns.GetHostName();
//получение ip
System.Net.IPAddress ip = System.Net.Dns.GetHostByName(host).AddressList[0];
Console.WriteLine("IP-адрес: " +ip.ToString());
Server server = new Server(PORT, Console.Out);
server.Work();
}
}
}
}using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace app
{
class Server
{
public TcpListener Listener; // объект принимающий tcp-клиентов
public List<ClientInfo> clients = new List<ClientInfo>();
public List<ClientInfo> NewClients = new List<ClientInfo>();
public static Server server;
static System.IO.TextWriter Out;
public Server(int Port, System.IO.TextWriter _Out)
{
Out = _Out;
Server.server = this;
//создаем слушателя для указанного порта
Listener = new TcpListener(IPAddress.Any, Port);
Listener.Start(); // запускаем его
}
public void Work()
{
Thread clientListener = new Thread(ListenerClients);
clientListener.Start();
while (true)
{
foreach (ClientInfo client in clients)
{
if (client.IsConnect)
{
NetworkStream stream = client.Client.GetStream();
while (stream.DataAvailable)
{
int ReadByte = stream.ReadByte();
if (ReadByte != -1)
{
client.buffer.Add((byte)ReadByte);
}
}
if (client.buffer.Count > 0)
{
Out.WriteLine("Resend");
foreach (ClientInfo otherClient in clients)
{
byte[] msg = client.buffer.ToArray();
client.buffer.Clear();
foreach (ClientInfo _otherClient in clients)
{
if (_otherClient != client)
{
try
{
_otherClient.Client.GetStream().Write(msg, 0, msg.Length);
}
catch
{
_otherClient.IsConnect = false;
_otherClient.Client.Close();
}
}
}
}
}
}
}
clients.RemoveAll(delegate (ClientInfo CI)
{
if (!CI.IsConnect)
{
Server.Out.WriteLine("Клиент отсоеденился");
return true;
}
return false;
});
if (NewClients.Count > 0)
{
clients.AddRange(NewClients);
NewClients.Clear();
}
}
}
//остановка сервера
~Server()
{
//если слушатель был создан
if (Listener != null)
{
//остановим его
Listener.Stop();
}
foreach (ClientInfo client in clients)
{
client.Client.Close();
}
}
static void ListenerClients()
{
while (true)
{
server.NewClients.Add(new ClientInfo(server.Listener.AcceptTcpClient()));
Out.WriteLine("Новый клиент");
}
}
}
class ClientInfo
{
public TcpClient Client;
public List<byte> buffer = new List<byte>();
public bool IsConnect;
public ClientInfo(TcpClient Client)
{
this.Client = Client;
IsConnect = true;
}
}
}Решение задачи: «Получение ip-адреса для сервера»
textual
Листинг программы
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System;
namespace Fchat
{
class Server
{
public TcpListener Listener; //объект, принимающий TCP клиентов
public List<ClientInfo> clients = new List<ClientInfo>();
public List<ClientInfo> NewClients = new List<ClientInfo>();
public static Server server;
static System.IO.TextWriter Out;
public Server(int Port, System.IO.TextWriter _Out)
{
Out = _Out;
Server.server = this;
//создаем слушателя для указанного порта
Listener = new TcpListener(IPAddress.Any, Port);
Listener.Start(); //запускаем его
}
public void Work()
{
Thread clientListener = new Thread(ListenerClients);
clientListener.Start();
while (true)
{
foreach (ClientInfo client in clients)
{
if (client.IsConnect)
{
NetworkStream stream = client.Client.GetStream();
while (stream.DataAvailable)
{
int ReadByte = stream.ReadByte();
if (ReadByte != -1)
{
client.buffer.Add((byte)ReadByte);
}
}
if (client.buffer.Count > 0)
{
Out.WriteLine("Resend");
foreach (ClientInfo otherClient in clients)
{
byte[] msg = client.buffer.ToArray();
client.buffer.Clear();
foreach (ClientInfo _otherClient in clients)
{
if (_otherClient != client)
{
try
{
_otherClient.Client.GetStream().Write(msg, 0, msg.Length);
}
catch
{
_otherClient.IsConnect = false;
_otherClient.Client.Close();
}
}
}
}
}
}
}
clients.RemoveAll(delegate (ClientInfo CI)
{
if (!CI.IsConnect)
{
Server.Out.WriteLine("Клиент отсоеденился.");
return true;
}
return false;
});
if (NewClients.Count > 0)
{
clients.AddRange(NewClients);
NewClients.Clear();
}
}
}
//остановка сервера
~Server()
{
//если слушатель был создан
if (Listener != null)
{
//остановим его
Listener.Stop();
}
foreach (ClientInfo client in clients)
{
client.Client.Close();
}
}
static void ListenerClients()
{
while (true)
{
server.NewClients.Add(new ClientInfo(server.Listener.AcceptTcpClient()));
Out.WriteLine("Новый клиент.");
}
}
}
class ClientInfo
{
public TcpClient Client;
public List<byte> buffer = new List<byte>();
public bool IsConnect;
public ClientInfo(TcpClient Client)
{
this.Client = Client;
IsConnect = true;
}
}
class Program
{
const int PORT = 90;
static void Main(string[] args)
{
Console.WriteLine("Запустить сервер? (Y / N)");
if (Console.ReadLine().Trim().ToUpper() == "Y")
{
//получение имени компъютера
IPHostEntry host = Dns.GetHostEntry("localhost");
IPAddress ip = host.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ip, 11000);
Socket sListener = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("IP адрес " + ip.ToString());
sListener.Bind(ipEndPoint);
sListener.Listen(10);
Server server = new Server(PORT, Console.Out);
server.Work();
}
}
}
}