Отправка и получение сообщений через сокеты - C#
Формулировка задачи:
Для начала , вот статья с аналоговым примером.
Вот метод для получения сообщений :
А вот отправки :
Никаких исключений на вольный брег не выбрасывалось , но при этом отправка сообщения не выходит.
Инициализация сокета проведена в соответсвии с тем как это сделано в статье.
Вот весь код :
void Listen(CancellationToken CancellToken){
MailSocket.Bind(ListenPoint);
while (!CancellToken.IsCancellationRequested)
{
byte[] bytes_Message = new byte[MailSocket.Available];
EndPoint RemotePoint = this.RemotePoint;
MailSocket.ReceiveFrom(bytes_Message,ref RemotePoint);
string result = ToString(bytes_Message);
DateTime.Now.ToShortTimeString().Print(Color.White,false);
result.PrintLine(Color.Green,false);
this.RemotePoint = RemotePoint as IPEndPoint;
}
}public void Send(string Message){
MailSocket.SendTo(ToBytes(Message) , RemotePoint);
}var c1 = new Chanel("c1","12345",new IPEndPoint(IPAddress.Loopback,4005));
var c2 = new Chanel("c2","1",new IPEndPoint(IPAddress.Loopback,4004));
c1.RemotePoint = c2.ListenPoint;
c1.BeginListen();
c2.BeginListen();
c1.Send("FF");
Console.ReadKey(true);using System;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Color = System.ConsoleColor;
namespace Mail
{
//Прочие вспомогательные классы , используются не все
public static class Console_Extensions
{
public static void Print(this string a , ConsoleColor PrescribedColor , bool LeaveColor = true){
var LastColor = Console.ForegroundColor;
Console.ForegroundColor = PrescribedColor;
Console.Write(a);
if (LeaveColor) Console.ForegroundColor = LastColor;
}
public static void PrintLine(this string a , ConsoleColor PrescribedColor ,bool LeaveColor = true){
a.Print(PrescribedColor,LeaveColor);
Console.WriteLine();
}
}
//Uses FonStart
public static class AdvancedConsole
{
public static void PressKey(string Message,Nullable<ConsoleKey> Key = null ){
Console.WriteLine(Message);
if (Key == null) Console.ReadKey(true);
else while (Console.ReadKey(true).Key != Key) {}
}
public static CancellationTokenSource FonStart(Action<CancellationToken> act){
var CancellToken = new CancellationTokenSource();
Task.Factory.StartNew( () => act(CancellToken.Token) );
return CancellToken;
}
}
//Not used
public class CReader
{
bool Disactivated;
readonly Dictionary<ConsoleKey,Action> Commands;
public CReader(int Capacity)
{
Commands = new Dictionary<ConsoleKey,Action>(Capacity);
}
public CReader()
{
Commands = new Dictionary<ConsoleKey,Action>();
}
public Action this[ConsoleKey key]
{
set
{
Commands.Add(key,value);
}
get
{
Action result;
Commands.TryGetValue(key,out result);
return result;
}
}
public void StartTakingCommands(){
Disactivated = false;
while (true)
{
Action act;
if ( Commands.TryGetValue( Console.ReadKey(true).Key , out act) )
act();
if (Disactivated) break;
}
}
public void StopTakingCommads()
{
Disactivated = true;
}
}
//============
//Основной код
public class Chanel
{
CancellationTokenSource CancellListen;
public readonly string Name;
public readonly string Password;
public readonly string Id;
public static Encoding MessageEncoding = Encoding.Unicode;
public Chanel(string Name, string Password , IPEndPoint ListenPoint)
{
this.Name = Name;
this.Password = Password;
MailSocket = NewUPDSocket();
this.ListenPoint = ListenPoint;
}
public IPEndPoint ListenPoint, RemotePoint = new IPEndPoint(IPAddress.Any,0);
Socket MailSocket;
static byte[] ToBytes(string s){
return MessageEncoding.GetBytes(s);
}
static string ToString(byte[] letter_Bytes){
return MessageEncoding.GetString(letter_Bytes);
}
static void Close(Socket local_Socket){
local_Socket.Shutdown(SocketShutdown.Both);
local_Socket.Close();
}
static Socket NewUPDSocket(){
return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
void Listen(CancellationToken CancellToken){
MailSocket.Bind(ListenPoint);
while (!CancellToken.IsCancellationRequested)
{
byte[] bytes_Message = new byte[MailSocket.Available];
EndPoint RemotePoint = this.RemotePoint;
MailSocket.ReceiveFrom(bytes_Message,ref RemotePoint);
string result = ToString(bytes_Message);
DateTime.Now.ToShortTimeString().Print(Color.White,false);
result.PrintLine(Color.Green,false);
this.RemotePoint = RemotePoint as IPEndPoint;
}
}
public void Send(string Message){
MailSocket.SendTo(ToBytes(Message) , RemotePoint);
}
public void BeginListen(){
CancellListen = AdvancedConsole.FonStart( Listen );
}
}
class Program
{
public static void Main()
{
var c1 = new Chanel("c1","12345",new IPEndPoint(IPAddress.Loopback,4005));
var c2 = new Chanel("c2","1",new IPEndPoint(IPAddress.Loopback,4004));
c1.RemotePoint = c2.ListenPoint;
c1.BeginListen();
c2.BeginListen();
c1.Send("FF");
Console.ReadKey(true);
}
}
}Решение задачи: «Отправка и получение сообщений через сокеты»
textual
Листинг программы
byte[] bytes_Message = new byte[MailSocket.Available];