TimerElapsedEvent not working in UDP Agent in C# - c#

My server is running continuously to receive data from Agent, but the Agent is getting closed after a single run.
Even my timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); is not working properly.
Agent Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Timers;
using System.Threading;
namespace HeartBeatAgent
{
public class Agent
{
static string clientdata = "IP1 Version 1";
static UdpClient UdpAgent = new UdpClient();
static System.Timers.Timer timer = new System.Timers.Timer();
static int ip = 127001;
static int port = 6060;
static IPEndPoint receivePoint;
static void Main(string[] args)
{
UdpAgent = new UdpClient(port);
receivePoint = new IPEndPoint(new IPAddress(ip), port);
Thread startClient = new Thread(new ThreadStart(startAgent));
//Start the Thread
startClient.Start();
}
public static void startAgent()
{
Console.WriteLine("This is Agent");
//Send Data
System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
string sendString = clientdata.ToString();
byte[] sendMsg = encode.GetBytes(sendString);
//Send to Server to corresponding port of server
UdpAgent.Send(sendMsg, sendMsg.Length, "localhost", 6767);
Console.WriteLine("Msg sent to server 4m agent");
//Receive Data from Server
byte[] recMsg = UdpAgent.Receive(ref receivePoint);
System.Text.ASCIIEncoding receive = new System.Text.ASCIIEncoding();
//Split it up
string[] temp = receive.GetString(recMsg).Split(new Char[] { ' ' });
Console.WriteLine(temp[2] + temp[1] + temp[0]);
**timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);**
timer.Interval = 10000;
timer.Start();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
startAgent();
}
}
}
Server Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace HeartBeatServer
{
public class Server
{
public static void Main(string[] args)
{
UdpClient UdpServer = new UdpClient(6767);
int count = 0;
while (true)
{
try
{
Dictionary<string, int> agentCount = new Dictionary<string, int>();
Console.WriteLine("This is server");
//Define a Receive point
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
//Receive Data from Agent
byte[] recData = UdpServer.Receive(ref RemoteIpEndPoint);
System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
//Split it up by space
string[] temp = encode.GetString(recData).Split(new Char[] { ' ' });
if (agentCount.ContainsKey(temp[0]))
{
var coun = agentCount[temp[0]];
agentCount.Add(temp[0], coun++);
Console.WriteLine(coun);
}
else
{
agentCount.Add(temp[0], count);
Console.WriteLine(temp[0], count);
//Re-send the Data to Agent
byte[] sendData = encode.GetBytes(System.DateTime.Now.ToString());
UdpServer.Send(sendData, sendData.Length, "localhost", 6060);
Console.WriteLine("Reply Message Sent to Agent 4m Server");
}
Console.WriteLine(temp[0] + temp[1] + temp[2]);
continue;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
}
I need to send message continuously to server at time interval of 5-10 seconds. Able to achieve first time only. Any idea where I am going wrong?

The problem is that you are creating a Thread, which calls a method and once that method ends the Thread will cease execution. Instead of using a thread, replace your Main method with this:
static void Main(string[] args)
{
UdpAgent = new UdpClient(port);
receivePoint = new IPEndPoint(new IPAddress(ip), port);
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
timer.Interval = 10000;
timer.Start();
}
and remove all timer related code from the startAgent method.

Related

C# Build simple server with event when new client connected

I tried to build a simple server in c# which wait for connections from clients. If a new client connects it makes a new Thread where it read from the client and send a message back to the client, that the server received the message from the client. My problem is that I try to raise an event when a new client connected to the server, but I just don't get what I should subscribe to.
Here is my code:
namespace ChatServer
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class Program
{
public static event EventHandler<NewClientConnectedEventArgs>NewClientConnected;
public static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Any, 80);
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
//listener += NewClientConnected(null, new NewClientConnectedEventArgs(client));
//FireNewClientHasConnected(null, eventargs);
}
}
public static void MakeNewConnection(TcpClient client)
{
Thread thread = new Thread(new ParameterizedThreadStart(NewClient));
thread.Start(client);
}
public static void NewClient(object data)
{
TcpClient client = (TcpClient)data;
string adress = client.Client.AddressFamily.ToString();
Console.WriteLine("{0} has connected!", adress);
NetworkStream ns = client.GetStream();
while (true)
{
byte[] receivedbuffer = new byte[8192];
int receivedbytes;
receivedbytes = ns.Read(receivedbuffer, 0, receivedbuffer.Length);
string message = Encoding.UTF8.GetString(receivedbuffer, 0, receivedbytes);
string newmessage = "The server received: " + message;
byte[] sendBuffer = Encoding.UTF8.GetBytes(newmessage);
ns.Write(sendBuffer, 0, sendBuffer.Length);
}
}
protected static void FireNewClientHasConnected(object sender, NewClientConnectedEventArgs args)
{
if (NewClientConnected != null)
{
MakeNewConnection(args.Client);
}
}
}
The part where I have the problem is the part which I comment out. Thanks in advance!
The call listener.AcceptTcpClient() blocks until a client connected. So just fire the event after the listener accepted the client.
class Program
{
public static void Main(string[] args)
{
var listener = new TcpListener(IPAddress.Any, 80);
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
MakeNewConnection(client);
}
}
public static void MakeNewConnection(TcpClient client)
{
var thread = new Thread(NewClient);
thread.Start(client);
}
public static void NewClient(object data)
{
var client = (TcpClient)data;
string adress = client.Client.AddressFamily.ToString();
Console.WriteLine("{0} has connected!", adress);
NetworkStream ns = client.GetStream();
while (true)
{
byte[] receivedbuffer = new byte[8192];
int receivedbytes = ns.Read(receivedbuffer, 0, receivedbuffer.Length);
string message = Encoding.UTF8.GetString(receivedbuffer, 0, receivedbytes);
string newmessage = "The server received: " + message;
byte[] sendBuffer = Encoding.UTF8.GetBytes(newmessage);
ns.Write(sendBuffer, 0, sendBuffer.Length);
}
}
}

TCP chat client/server won't work off localhost

I am currently learning to program a chat room application that uses a server. So far everything works fine if I run the server and multiple instances of the application on a single machine. When I try to run the server on one machine and the actual chat application from another, I get an exception that reads "a connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond (Ipaddress)(port)"
Server side code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Text;
using System.Threading;
namespace ChatAppServer
{
class Program
{
public static Hashtable ClientList = new Hashtable();
const int PORT = 321;
string localIp;
static void Main(string[] args)
{
TcpListener sckServer = new TcpListener(PORT);
TcpClient sckClient = default(TcpClient);
int counter = 0;
sckServer.Start();
Console.WriteLine("Chat Server is now Running ....");
counter = 0;
//Parser myParser = new Parser();
while (true)
{
counter = counter + 1;
sckClient = sckServer.AcceptTcpClient();
string clientData = "";
byte[] recieveData = new byte[10025];
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
ClientList.Add(clientData, sckClient);
Broadcast(clientData + " joined the chat", clientData, false);
Console.WriteLine(clientData + " connected to the chat");
handleClient client = new handleClient();
client.ClientStart(sckClient, clientData, ClientList);
}
sckClient.Close();
sckServer.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void Broadcast(string msg, string userName, bool flag)
{
foreach (DictionaryEntry Item in ClientList)
{
TcpClient sckBroadcast;
sckBroadcast = (TcpClient)Item.Value;
NetworkStream broadcastStream = sckBroadcast.GetStream();
Byte[] broadcastData = null;
if (flag == true)
{
broadcastData = Encoding.ASCII.GetBytes(userName + ": " + msg);
}
else
{
broadcastData = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastData, 0, broadcastData.Length);
broadcastStream.Flush();
}
}
public class handleClient
{
TcpClient sckClient;
string clId;
Hashtable ClientList;
public void ClientStart(TcpClient inSckClient, string clientId, Hashtable clist) {
this.sckClient = inSckClient;
this.clId = clientId;
this.ClientList = clist;
Thread ctThread = new Thread(runChat);
ctThread.Start();
}
private void runChat() {
int requestCount = 0;
byte[] recieveData = new byte[10025];
string clientData = "";
string rCount = null;
while ((true))
{
try
{
requestCount += 1;
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
Console.WriteLine(clId + " : " + clientData);
rCount = Convert.ToString(requestCount);
Program.Broadcast(clientData, clId, true);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
}
Chat room application code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Need for the application
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ChatApp
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient sckClient = new System.Net.Sockets.TcpClient();
NetworkStream svrStream = default(NetworkStream);
string recieveData = null;
public Form1()
{
InitializeComponent();
btnSend.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
recieveData = "Connected to Server";
msg();
int serverPort = Convert.ToInt32(txtServerPort.Text);
sckClient.Connect(txtServerIp.Text, serverPort);
svrStream = sckClient.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtUserName.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
Thread ctThread = new Thread(MessageCallBack);
btnSend.Enabled = true;
btnConnect.Enabled = false;
txtUserName.Enabled = false;
txtServerIp.Enabled = false;
txtServerPort.Enabled = false;
ctThread.Start();
}
private void MessageCallBack()
{
while(true)
{
svrStream = sckClient.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = sckClient.ReceiveBufferSize;
svrStream.Read(inStream, 0, buffSize);
string returnData = System.Text.Encoding.ASCII.GetString(inStream);
recieveData = "" + returnData;
msg();
}
}
//function to display data strings
private void msg()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(msg));
}
else
{
lstMessage.Items.Add(recieveData);
}
}
private void btnSend_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtMessage.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
txtMessage.Text = "";
}
I have two troubles with your code :
Do not use .ReceiveBufferSize value because it's a different value of your byte array length. And you can have an index out of range exception.
You have a problem of concurrency in the server side. More than 1 thread try to access to the ClientList and this collection is not thread-safe.
To resolve this, you can use the lock keyword
private static object _lock = new object();
//...
lock (_lock)
{
ClientList.Add(clientData, sckClient);
}
lock (_lock)
{
Broadcast(clientData + " joined the chat", clientData, false);
}
//...
lock (_lock)
{
Program.Broadcast(clientData, clId, true);
}
As you're a beginner, i would give you some tips.
Try to use the asynchronous network functions (better than raw threads), an example there.
There is a lot of tutorials about safety with severals connections in C# (with some thing else, better, than the lock keyword).

How to send messages to all clients in multithread chat server?

Sorry for asking about the 'same' thing over and over again. It's yet another edition of the chat. With a lot of searching around I've finally found out how to pass the client list (or at least I hope so) to the Chat function.
However I don't know if this is even supposed to work:
Everytime a client connects :
clients.Add(clientSocket);
var ctThread = new System.Threading.Thread(() => Chat(clients));
where the Chat function hopefully correctly receives the clients via
public void Chat(List<TcpClient> clients)
and then writes this out
foreach (var client in clients)
{
writer.Write(message);
}
With the client having 2 threads (not sure if they can actually read/write at the same time)
Thread ctThread = new Thread(Write);
Thread ctThread2 = new Thread(Read);
ctThread2.Start();
ctThread.Start();
Did I pass the client list to the function properly? and can it actually correctly send the messages? Because right now the server is not responding to anything that I type on the client.
Full code:
Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace MultiServeris
{
class Multiserveris
{
static void Main(string[] args)
{
TcpListener ServerSocket = new TcpListener(1000);
ServerSocket.Start();
List<TcpClient> clients = new List<TcpClient>();
Console.WriteLine("Server started.");
while (true)
{
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
handleClient client = new handleClient();
clients.Add(clientSocket);
client.startClient(clientSocket,clients);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket, List<TcpClient> clients)
{
this.clientSocket = inClientSocket;
var ctThread = new System.Threading.Thread(() => Chat(clients));
}
public void Chat(List<TcpClient> clients)
{
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
while (true)
{
string message = reader.ReadString();
foreach (var client in clients)
{
writer.Write(message);
}
}
}
}
}
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Klientas
{
class Klientas
{
public static void Write()
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
string str = Console.ReadLine();
BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
writer.Write(str);
}
}
public static void Read()
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
string message = reader.ReadString();
Console.WriteLine(message);
}
}
static void Main(string[] args){
Thread ctThread = new Thread(Write);
Thread ctThread2 = new Thread(Read);
ctThread2.Start();
ctThread.Start();
}
}
}
TCP is not design for broadcasting which is why you're having to loop through all your clients. A better approach would be to use a protocol that supports brodcast use the SignalR Framework or if you want baremetal access use UDP. Here's a great SignalR chat example.
https://dhavalupadhyaya.wordpress.com/tag/signalr-chat-example/

C# Connecting two tcp sockets together

I'm not sure if the title is all that informative.
I am trying to find/write a socket server that will accept a connection from the client (telnet) and then on behalf of the connected client, connect to one of four telnet servers inside the network.
Once connected I keep a counter of how many connections there are, and then if there are 4 total connections, disallow any new connections until one of the four is available.
I have written this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static int nodeCount = 4;
static int currentNode = 1;
static void Main(string[] args)
{
ServerProgram server = new ServerProgram();
}
class ServerProgram
{
private TcpListener tcpPrimaryListener;
private Thread listenThread;
public ServerProgram()
{
this.tcpPrimaryListener = new TcpListener(IPAddress.Any, 23);
Console.WriteLine("Telnet BBS Port Concentrator Server Started.");
Console.WriteLine("--------------------------------------------");
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpPrimaryListener.Start();
while (true)
{
TcpClient client = this.tcpPrimaryListener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
if (currentNode <= nodeCount)
{
Console.WriteLine("Connection thread created.");
StreamWriter swStream;
StreamWriter swStream2;
StreamReader srStream;
StreamReader srStream2;
TcpClient tcpClient = (TcpClient)client;
NetworkStream tcpClientStream = tcpClient.GetStream();
TcpClient telnet = new TcpClient("192.168.100.5" + currentNode, 23);
NetworkStream telnetStream = telnet.GetStream();
currentNode++;
while (true)
{
srStream = new StreamReader(tcpClient.GetStream());
swStream2 = new StreamWriter(tcpClient.GetStream());
srStream2 = new StreamReader(telnet.GetStream());
swStream = new StreamWriter(telnet.GetStream());
swStream.Write(srStream.ReadToEnd());
swStream2.Write(srStream2.ReadToEnd());
}
}
}
}
}
}
I've changed this example multiple times, so I don't really know anymore what I have and have not tried. I'm willing to try anything.
The purpose is actually running this to allow one telnet port open through the firewall, and allowing connections into a small network of DOS machines running telnet fossil driver BBS software. I would just like to redirect telnet traffic to an available system using only one port.
The problem is that I cannot figure out how to actually connect the two sockets together and pass data between them as it happens. The incoming socket and the socket I created on behalf of the server to the server.
Thanks.
UPDATE:
This is what is working for me, I'm still looking over for bugs but it's working so far.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int nodeCount = 2;
static int currentNode = 1;
static void Main(string[] args)
{
ServerProgram server = new ServerProgram();
}
class ServerProgram
{
private TcpListener tcpPrimaryListener;
private Thread listenThread;
public ServerProgram()
{
this.tcpPrimaryListener = new TcpListener(IPAddress.Any, 23);
Console.WriteLine("Telnet BBS Port Concentrator Server Started.");
Console.WriteLine("--------------------------------------------");
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpPrimaryListener.Start();
while (true)
{
TcpClient client = this.tcpPrimaryListener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
string noNodes = "Sorry all nodes are occupied.";
if (currentNode <= nodeCount)
{
Console.WriteLine("Client connected.");
TcpClient tcpClient = (TcpClient)client;
NetworkStream tcpClientStream = tcpClient.GetStream();
TcpClient telnet = new TcpClient("10.24.9.11", 23);
//TcpClient telnet = new TcpClient("192.168.100.5" + currentNode, 23);
NetworkStream telnetStream = telnet.GetStream();
currentNode++;
ByPass linkedSockets = new ByPass(tcpClientStream, telnetStream);
}
else
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream tcpClientStream = tcpClient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
tcpClientStream.Write(Encoding.ASCII.GetBytes(noNodes), 0, noNodes.Length);
}
}
}
public class ByPass
{
public ByPass(Stream s1, Stream s2)
{
var cTokenSource = new CancellationTokenSource();
var cToken = cTokenSource.Token;
Task.Factory.StartNew(() => Process(s1, s2, cToken, cTokenSource), cToken);
Task.Factory.StartNew(() => Process(s2, s1, cToken, cTokenSource), cToken);
cToken.Register(() => cancelNotification());
}
public void Process(Stream s1, Stream s2, CancellationToken ct, CancellationTokenSource cTokenSource)
{
byte[] buf = new byte[0x10000];
while (true)
{
if (ct.IsCancellationRequested)
{
break;
}
try
{
int len = s1.Read(buf, 0, buf.Length);
s2.Write(buf, 0, len);
}
catch
{
s1.Close(); s2.Close();
cTokenSource.Cancel();
break;
}
}
}
}
static void cancelNotification()
{
Console.WriteLine("Client disconnected.");
currentNode--;
}
}
}
I think, you can create a class similar to below to pass data between two streams
public class ByPass
{
public ByPass(Stream s1, Stream s2)
{
Task.Factory.StartNew(() => Process(s1, s2));
Task.Factory.StartNew(() => Process(s2, s1));
}
public void Process(Stream sIn, Stream sOut)
{
byte[] buf = new byte[0x10000];
while (true)
{
int len = sIn.Read(buf, 0, buf.Length);
sOut.Write(buf, 0, len);
}
}
}
I have made little changes and it works perfect on my side
public class StreamTransmitter
{
static TaskCompletionSource<bool> ts;
public static async Task Start(Stream s1, Stream s2, CancellationToken token)
{
ts = new TaskCompletionSource<bool>();
Process(s1, s2, token);
Process(s2, s1, token);
await ts.Task;
}
private static async Task Process(Stream sIn, Stream sOut, CancellationToken token)
{
byte[] buf = new byte[0x10000];
int len = 0;
do
{
len = await sIn.ReadAsync(buf, 0, buf.Length, token);
await sOut.WriteAsync(buf, 0, len, token);
}
while (len > 0 && !token.IsCancellationRequested);
ts.SetResult(true);
}
}

.NET UDP Socket Send Increasing Memory Usage

I'm seeing an issue where I have a UDP client & server exchanging messages frequently and the memory usage for both entities is increasing at a rate of approximately 8K per second (althoughly ultimately, this depends on the rate of commuinications between them) as observed in the Task Manager.
To illustrate this as simply as possible, I've created a sample based upon the MSDN Using UDP Services http://msdn.microsoft.com/en-us/library/tst0kwb1.aspx.
The server:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UDPListener
{
private const int listenPort = 11000;
private static void StartListener()
{
bool done = false;
UInt32 count = 0;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Loopback, listenPort);
try
{
while (!done)
{
byte[] bytes = listener.Receive(ref groupEP);
if ("last packet" == System.Text.Encoding.UTF8.GetString(bytes))
{
done = true;
Console.WriteLine("Done! - rx packet count: " + Convert.ToString(count));
}
else
{
count++;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
public static int Main()
{
StartListener();
return 0;
}
}
And the client:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace UDPSender
{
class Program
{
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPAddress broadcast = IPAddress.Parse(IPAddress.Loopback.ToString());
byte[] sendbuf = Encoding.ASCII.GetBytes("test string");
IPEndPoint ep = new IPEndPoint(broadcast, 11000);
for (int i = 0; i < 500; i++)
{
s.SendTo(sendbuf, ep);
System.Threading.Thread.Sleep(50);
}
s.SendTo(Encoding.ASCII.GetBytes("last packet"), ep);
s.Dispose();
}
}
}
I've tried both using the Socket interface directly and UDPClient, dropping the client socket after each transmission, explicit GC.Collect etc. to no avail.
Any ideas what's going on here - I can't belive this is a fundamental issue with .NET, there must be an issue with my code/the sample....
Try this :
bytes = null;

Categories

Resources