-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
71 lines (60 loc) · 2.18 KB
/
Copy pathProgram.cs
File metadata and controls
71 lines (60 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleUdpChat
{
class ChatController
{
private UdpClient _udpClient;
private readonly IPAddress _multicastAddress;
private readonly IPEndPoint _endPoint;
public ChatController()
{
_multicastAddress = IPAddress.Parse("239.0.0.1");
_udpClient = new UdpClient();
_udpClient.JoinMulticastGroup(_multicastAddress);
_endPoint = new IPEndPoint(_multicastAddress, 1408);
}
public void SendMessage(string msg)
{
byte[] buff = Encoding.UTF8.GetBytes(msg);
_udpClient.Send(buff, buff.Length, _endPoint);
}
public void Listener()
{
UdpClient listener = new UdpClient();
listener.ExclusiveAddressUse = false;
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 1408);
listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
listener.Client.Bind(localEndPoint);
listener.JoinMulticastGroup(_multicastAddress);
Console.WriteLine("---CHAT---");
Console.WriteLine("Digite 'sair' para finalizar a aplicação...");
Console.WriteLine("Conectado ao servidor na porta: " + _endPoint.Port);
while (true)
{
byte[] data = listener.Receive(ref localEndPoint);
Console.WriteLine(localEndPoint + " --> " + Encoding.UTF8.GetString(data));
}
}
class Program
{
static void Main(string[] args)
{
ChatController controller = new ChatController();
new Thread(controller.Listener) { IsBackground = true }.Start();
while (true)
{
controller.SendMessage(Console.ReadLine());
if (Console.ReadLine().Contains("sair"))
break;
}
}
}
}
}