using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace UdpSample
{
class Chat
{
private static IPAddress remoteIPAddress;
private static int remotePort;
private static int localPort;
[STAThread]
static void Main(string[] args)
{
try
{
// We get the data necessary for the connection
Console.WriteLine("Specify a local port");
localPort = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Specify Remote Port");
remotePort = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Specify Remote IP Address");
remoteIPAddress = IPAddress.Parse(Console.ReadLine());
// We create a stream for listening
Thread tRec = new Thread(new ThreadStart(Receiver));
tRec.Start();
while (true)
{
Send(Console.ReadLine());
}
}
catch (Exception ex)
{
Console.WriteLine("An exception has occurred: " + ex.ToString() + "\n " + ex.Message);
}
}
private static void Send(string datagram)
{
// Create UdpClient
UdpClient sender = new UdpClient();
// Создаем endPoint по информации об удаленном хосте
//We create endPoint on the information on a remote host
IPEndPoint endPoint = new IPEndPoint(remoteIPAddress, remotePort);
try
{
// Convert data to byte array
byte[] bytes = Encoding.UTF8.GetBytes(datagram);
// Send data
sender.Send(bytes, bytes.Length, endPoint);
}
catch (Exception ex)
{
Console.WriteLine("An exception has occurred: " + ex.ToString() + "\n " + ex.Message);
}
finally
{
// Закрыть соединение
sender.Close();
}
}
public static void Receiver()
{
// Create a UdpClient to read incoming data
UdpClient receivingUdpClient = new UdpClient(localPort);
IPEndPoint RemoteIpEndPoint = null;
try
{
Console.WriteLine(
"\n-----------*******General chat*******-----------");
while (true)
{
// Waiting for a datagram
byte[] receiveBytes = receivingUdpClient.Receive(
ref RemoteIpEndPoint);
// Convert and display data
string returnData = Encoding.UTF8.GetString(receiveBytes);
Console.WriteLine(" --> " + returnData.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine("An exception has occurred: " + ex.ToString() + "\n " + ex.Message);
}
}
}
}