Цели: Я хочу иметь возможность соединить два компьютера хотя бы через Radmin, без лишних хлопот на стороне клиента, потому что все мои друзья им пользуются. Или найдите другой способ подключения.
мой друг пытался дать права программе в настройках брандмауэра в панели управления, но не помогло
кодируйте, если кому нужно:
Код: Выделить всё
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace RadminMessenger
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("CONNECT/HOST?");
string answer = Console.ReadLine();
using Socket serverSocket = new(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
if (answer.ToLower() == "host")
{
IPEndPoint iPEndPoint = new(IPAddress.Any, 0);
serverSocket.Bind(iPEndPoint);
serverSocket.Listen();
Console.WriteLine($"Waiting for connection on {serverSocket.LocalEndPoint}");
using Socket friend = serverSocket.Accept();
Console.WriteLine($"You are connected with {friend.RemoteEndPoint}");
Task receiveMessageLoop = new(() => GetMessagesInLoopAsync(friend));
receiveMessageLoop.Start();
SendMessagesInLoop(friend);
}
else if (answer.ToLower() == "connect")
{
using Socket friend = new(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Enter ip address");
string ip = Console.ReadLine();
ip = ip == "0" ? "127.0.0.1" : ip;
Console.WriteLine("Enter port: ");
int port = int.Parse(Console.ReadLine());
friend.Connect(ip, port);
Console.WriteLine("Connected!");
Task receiveMessageLoop = new(() => GetMessagesInLoopAsync(friend));
receiveMessageLoop.Start();
SendMessagesInLoop(friend);
}
} catch (Exception e)
{
Console.WriteLine(e);
Console.ReadKey();
}
}
private static void SendMessagesInLoop(Socket friend)
{
while (true)
{
string messageToSend = "";
ConsoleKeyInfo keyInfo = new();
while (keyInfo.Key != ConsoleKey.Enter)
{
keyInfo = Console.ReadKey();
if (keyInfo.Key == ConsoleKey.Enter)
break;
else if (keyInfo.Key == ConsoleKey.Backspace)
{
Console.Write(" \b");
messageToSend = messageToSend.Remove(messageToSend.Length-1);
continue;
}
messageToSend += keyInfo.KeyChar;
}
ClearCurrentConsoleLine();
Console.WriteLine($"[You] {messageToSend}");
byte[] buffer = Encoding.UTF8.GetBytes(messageToSend);
friend.Send(buffer);
}
}
private static void GetMessagesInLoopAsync(Socket friend)
{
while (true)
{
byte[] buffer = new byte[512];
int bytesRead = friend.Receive(buffer);
Array.Resize(ref buffer,bytesRead);
Console.WriteLine($"[{friend.RemoteEndPoint}] "+Encoding.UTF8.GetString(buffer));
}
}
public static void ClearCurrentConsoleLine()
{
int currentLineCursor = Console.CursorTop;
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, currentLineCursor);
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... pplication
Мобильная версия