How operate more than one Socket in ListViewItem? - c#

I have 2 Sockets in server and client respectively (where client connect to server), on server i have one class that contains some informations of each client like IP, Socket and ID.
For each connection accepted i add the last client connected to this List, this way i have a list (that is a object) of clients. And also each client is added in one ListView where is assigned the object referent to this client, on Tag property of ListViewItem. This is one of way that can help later if you want send a message to a specific client.
Like you can see this List of clients is referent only to 1 Socket that listen in a determinated port number. Now already that i have 2 Sockets in each side (server and client), how i can make if i want send a message from second Socket of server to the second Socket on client? for example, is possible assign more than 1 object to Tag property of ListViewItem (only a idea)?
Below is my code (server, compatible only with 1 Socket and 1 object (List of client)):
Form:
namespace mainForm
{
public partial class frmMain : Form
{
Listener server;
Thread start;
public frmMain()
{
InitializeComponent();
server = new Listener();
}
private void startToolStripMenuItem_Click(object sender, EventArgs e)
{
start = new Thread(listen);
start.Start();
}
private void listen()
{
server.BeginListen(101); // Select a port to listen
server.Received += new Listener.ReceivedEventHandler(server_Received);
server.Disconnected += new Listener.DisconnectedEventHandler(server_Disconnected);
}
private void server_Disconnected(Listener l, Info i)
{
Invoke(new _Remove(Remove), i);
}
private void server_Received(Listener l, Info i, string received)
{
string[] cmd = received.Split('|');
int inc;
for (inc = 0; inc < cmd.Length; inc++)
{
switch (cmd[inc].ToString())
{
case "CMD1":
Invoke(new _Add(Add), i, cmd[2] + " - " + cmd[3]);
break;
case "CMD2":
// Other code here
break;
}
}
}
private delegate void _Add(Info i, string computer);
private void Add(Info i, string computer)
{
string[] splitIP = i.RemoteAddress.Split(':');
ListViewItem item = new ListViewItem();
item.Text = i.ID.ToString();
item.SubItems.Add(splitIP[0]);
item.SubItems.Add(computer);
item.Tag = i;
lvConnections.Items.Add(item);
}
private delegate void _Remove(Info i);
private void Remove(Info i)
{
foreach (ListViewItem item in lvConnections.Items)
{
if ((Info)item.Tag == i)
{
item.Remove();
break;
}
}
}
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in lvConnections.SelectedItems)
{
Info client = (Info)item.Tag;
client.Send("DISCONNECT" + Environment.NewLine);
}
}
Listener:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
class Listener
{
Socket s;
public List<Info> clients;
public delegate void ReceivedEventHandler(Listener l, Info i, string received);
public event ReceivedEventHandler Received;
public delegate void DisconnectedEventHandler(Listener l, Info i);
public event DisconnectedEventHandler Disconnected;
bool listening = false;
public Listener()
{
clients = new List<Info>();
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public bool Running
{
get { return listening; }
}
public void BeginListen(int port)
{
s.Bind(new IPEndPoint(IPAddress.Any, port));
s.Listen(100);
s.BeginAccept(new AsyncCallback(AcceptCallback), s);
listening = true;
}
public void StopListen()
{
if (listening == true)
{
s.Close();
listening = false;
}
}
void AcceptCallback(IAsyncResult ar)
{
Socket handler = (Socket)ar.AsyncState;
Socket sock = handler.EndAccept(ar);
Info i = new Info(sock);
clients.Add(i);
sock.BeginReceive(i.buffer, 0, i.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), i);
handler.BeginAccept(new AsyncCallback(AcceptCallback), handler);
}
void ReadCallback(IAsyncResult ar)
{
Info i = (Info)ar.AsyncState;
try
{
int rec = i.sock.EndReceive(ar);
if (rec != 0)
{
string data = Encoding.UTF8.GetString(i.buffer, 0, rec);
Received(this, i, data);
}
else
{
Disconnected(this, i);
return;
}
i.sock.BeginReceive(i.buffer, 0, i.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), i);
}
catch (Exception ex)
{
Disconnected(this, i);
i.sock.Close();
clients.Remove(i);
}
}
}
Info:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class Info
{
public Socket sock;
public Guid ID;
public string RemoteAddress;
public byte[] buffer = new byte[8192];
public Info(Socket sock)
{
this.sock = sock;
ID = Guid.NewGuid();
RemoteAddress = sock.RemoteEndPoint.ToString();
}
public void Send(string data)
{
byte[] buffer = Encoding.UTF8.GetBytes(data);
sock.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback((ar) =>
{
sock.EndSend(ar);
}), buffer);
}
}
EDITION:
Here is what code above already makes =>
And here is like i wants make (also work with Socket 02 in a selected client) =>

Related

Thread sending data to wrong client. Is this a thread safety issue?

I'm currently developing a server that deals with clients using a consumer/producer approach with threads and a blocking collection as shown below:
public class NetworkClient
{
private bool _started = false;
private int _clientId;
private readonly Socket _socket;
private static AutoResetEvent _lastMessageWasAckd = new AutoResetEvent(true);
private static BlockingCollection<byte[]> _messageQueue = new BlockingCollection<byte[]>();
public NetworkClient(Socket socket, int clientId)
{
this._socket = socket;
this._clientId = clientId;
}
public int getClientID() {
return _clientId;
}
public void SendMessage(string message)
{
Console.WriteLine("Adding to player's sending queue " + _clientId);
_messageQueue.Add(Encoding.ASCII.GetBytes(message));
}
public void Start()
{
Thread receiver = new Thread(new ThreadStart(ReceivingThreadProc));
Thread sender = new Thread(new ThreadStart(SendingThreadProc));
receiver.Start();
sender.Start();
this._started = true;
}
public void Stop()
{
this._started = false;
}
private void ReceivingThreadProc()
{
byte[] bytes = new byte[1024];
string data;
try
{
while (_started && _socket.Connected)
{
int numByte = this._socket.Receive(bytes);
data = Encoding.ASCII.GetString(bytes, 0, numByte);
if (numByte == 0)
{
break;
}
if (data == "ACK")
{
_lastMessageWasAckd.Set();
continue;
}
// Acknowledge the message
_socket.Send(Encoding.ASCII.GetBytes("ACK"));
ServerReceiver.onEvent(this._clientId, data);
}
}
catch (Exception e)
{
this._socket.Close();
}
}
private void SendingThreadProc()
{
while (_started && _socket.Connected)
{
_lastMessageWasAckd.WaitOne();
byte[] message = _messageQueue.Take();
Console.WriteLine("Sending the following message to client number: " + _clientId);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(message));
_socket.Send(message);
_lastMessageWasAckd.Reset();
}
}
}
There will be an instance of NetworkClient created for every client that connects for the server. The issue is that sometimes a message is queued to be sent to client 1 (this is confirmed by the Console.Writeline in the SendMessage method) however that message is sent to client 0 (Shown by the console writeline in the SendingThreadProc method) instead. Is this due to a thread safety issue, or am I missing something entirely? This typically happens when two messages are sent right after one another.
Any help would be greatly appreciated.
EDIT:
As many people rightly pointed out I haven't added where I call SendMessage I'll put this class down below:
class NetworkServer
{
private int latestClient = 0;
private ServerReceiver _serverReceiver;
private static readonly Dictionary<int, NetworkClient> clients = new Dictionary<int, NetworkClient>();
public NetworkServer()
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 5656);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this._serverReceiver = new ServerReceiver();
this._serverReceiver.start();
try
{
listener.Bind(endpoint);
listener.Listen(10);
while (true)
{
Socket clientSocket = listener.Accept();
this.OnClientJoin(clientSocket);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static void SendClientMessage(int clientId, string package, CommandType commandType,
Dictionary<string, object> data = null)
{
if (data == null)
{
data = new Dictionary<string, object>();
}
SendClientMessageRaw(clientId, new NetworkCommand(clientId, package, commandType, data).ToJson());
}
public static void SendClientMessageRaw(int id, string message)
{
Console.WriteLine("Supposed to send to client number " + clients[id].getClientID());
clients[id].SendMessage(message);
}
private void OnClientJoin(Socket socket)
{
// Add client to array, perform handshake?
NetworkClient networkClient = new NetworkClient(socket, latestClient);
clients.Add(latestClient, networkClient);
Console.WriteLine("player added :" + latestClient);
networkClient.Start();
latestClient++;
if (latestClient == 2)
{
SendClientMessage(1, "Test", CommandType.Ping, null);
}
}
Could it be because your message queue is static and therefore shared between all NetworkClients? Meaning client A can pick up a message for client B?
Might be as easy as removing static from the properties.

How to fix when trying to add data values to a listbox from another form

I am having an issue while trying to add data to a listbox from my main form, I am trying to add data to that list from a new class in my project, I need that new class to be able to add data to my listbox without errors, I am trying to use a invoke and I am getting the following error (System.InvalidOperationException: 'Invoke or BeginInvoke cannot be called on a control until the window handle has been created.') I have seen that error in other questions in stack overflow but similar to my issue, I will be adding both classes of my code here, one is the main class and the other a second class I created that will need to add data to the listbox. the data is coming from a telnet tcp/ip and port 23 that connection is working fine, the problem is adding that data to my listbox.
Main class calling the functions from my other class
namespace BarcodeReceivingApp
{
//TelnetConnection stopConnection = new TelnetConnection();
public partial class BarcodeReceivingForm : Form
{
//GLOBAL VARIABLES
const string Hostname = "myip";
private const int Port = 23;
public BarcodeReceivingForm()
{
InitializeComponent();
}
private void btn_ConnectT_Click(object sender, EventArgs e)
{
var readData = new TelnetConnection(Hostname, Port);
readData.ServerSocket(Hostname, Port);
}
private void btn_StopConnection_Click(object sender, EventArgs e)
{
//var connection = new TelnetConnection(Hostname, Port);
// connection.CloseConnection();
}
}
}
class that will change the data of my listbox from the main class.
namespace BarcodeReceivingApp
{
public class TelnetConnection
{
public BarcodeReceivingForm BcForm = new BarcodeReceivingForm();
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private string _hostname;
private int _port;
public TelnetConnection(string hostname, int port)
{
this._hostname = hostname;
this._port = port;
}
public void ServerSocket(string ip, int port)
{
try
{
_client = new TcpClient(ip, port);
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
//Assign networkstream
_networkStream = _client.GetStream();
//start socket read/write thread
_readWriteThread = new Thread(ReadWrite);
_readWriteThread.Start();
}
public void ReadWrite()
{
//Set up connection loop
while (true)
{
var command = "test";
if (command == "STOP1")
break;
//write(command);
var received = Read();
BcForm.lst_BarcodeScan.Invoke(new Action (() => BcForm.lst_BarcodeScan.Items.Add(received)));
}
}
public string Read()
{
byte[] data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
public void CloseConnection()
{
_networkStream.Close();
_client.Close();
}
}
}
the final results like I said is my ReadWrite method when running the loop will add the data to my listbox from my main form class
here the image where I get the error
Image of Error
Write your second class like this
using System;
using System.Threading;
using System.Windows.Forms;
namespace BarcodeReceivingApp {
public class TelnetConnection {
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private string _hostname;
private int _port;
private Form foo;
public TelnetConnection(string hostname, int port)
{
this._hostname = hostname;
this._port = port;
}
public void ServerSocket(string ip, int port,Form f)
{
this.foo = f;
try
{
_client = new TcpClient(ip, port);
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
_networkStream = _client.GetStream();
_readWriteThread = new Thread(ReadWrite());
_readWriteThread.Start();
}
public void ReadWrite()
{
while (true)
{
var command = "test";
if (command == "STOP1")
break;
//write(command);
var received = Read();
if (foo.lst_BarcodeScan.InvokeRequired)
{
foo.lst_BarcodeScan.Invoke(new MethodInvoker(delegate {foo.lst_BarcodeScan.Items.Add(received);}));
}
}
}
public string Read()
{
byte[] data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
public void CloseConnection()
{
_networkStream.Close();
_client.Close();
}
}
}
Then use it like this from your main class:
private void btn_ConnectT_Click(object sender, EventArgs e)
{
var readData = new TelnetConnection(Hostname, Port);
readData.ServerSocket(Hostname, Port, this);
}

How to implement Socket server that accept more message

I want to send at real time some data from Android application to server.
So I'm building a simple socket Server in c# like this:
class Program
{
private Socket listener;
static void Main(string[] args)
{
Program p = new Program();
p.socketServer();
}
public void socketServer()
{
int MAXBUFFER = 1024;
Console.WriteLine("SOCKET STARTED");
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 8080));
listener.Listen(10);
while (true)
{
Console.WriteLine("WAITING CONNECTION");
Socket socket = listener.Accept();
string receivedMessage = string.Empty;
while (true)
{
byte[] receivedBytes = new byte[MAXBUFFER];
int numBytes = socket.Receive(receivedBytes);
receivedMessage += Encoding.ASCII.GetString(receivedBytes, 0, numBytes);
if (receivedMessage.IndexOf("\n") > -1)
{
Console.WriteLine("MESSAGE FROM CLIENT: {0}", receivedMessage);
//break;
}
}
Console.WriteLine("MESSAGE FROM CLIENT: {0}", receivedMessage);
string replyMessage = "MESSAGE RECEIVED";
byte[] replyBytes = Encoding.ASCII.GetBytes(replyMessage);
}
}
public void shutdownServer()
{
listener.Shutdown(SocketShutdown.Both);
listener.Close();
}
}
And I'm building this class to send data from Android application:
public class TcpClient {
public static final String SERVER_IP = "192.168.110.50"; // computer IP address
public static final int SERVER_PORT = 8080;
private String mServerMessage;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
private PrintWriter mBufferOut;
private BufferedReader mBufferIn;
private Socket socket;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* #param message text entered by client
*/
public void sendMessage(String message) {
socket.isConnected();
if (mBufferOut != null /*&& !mBufferOut.checkError()*/) {
mBufferOut.println(message);
}
}
/**
* Close the connection and release the members
*/
public void stopClient() {
Log.i("Debug", "stopClient");
// send mesage that we are closing the connection
//sendMessage(Constants.CLOSED_CONNECTION + "Kazy");
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
//create a socket to make the connection with the server
socket = new Socket(SERVER_IP, SERVER_PORT);
//socket.connect(socket.getRemoteSocketAddress());
socket.isConnected();
try {
Log.i("Debug", "inside try catch");
mBufferOut = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
And in the MainActivity I use this code:
tcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
//publishProgress(message);
}
});
tcpClient.run();
After connect to server i user this code to send message:
for(int i=0; i<10; i++){
tcpClient.sendMessage("test " + i);
}
The problem is that only the first message arrive to the server. I think that the problem is on the socket server that lost the connection with the client.

Multiple TcpListeners not working

I made an "Acceptor" class which in the cunstroctor it accepts an amount of TcpListeners. Starting from port 8484 and above.
class Acceptor
{
private List<TcpListener> Listeners;
private static int clientCount = 0;
private static int portStart = 8484;
public Acceptor(int capacity)
{
Listeners = new List<TcpListener>(capacity);
for (int i = 0; i < capacity; i++)
{
Listeners.Add(new TcpListener(IPAddress.Any, portStart));
portStart++;
}
foreach (TcpListener listener in Listeners)
{
try
{
listener.Start();
listener.BeginAcceptSocket(new AsyncCallback(EndAccept), null);
}
catch (SocketException ex)
{
Debug.WriteLine("Failed to start TcpListener, Error {0}.", ex.Message);
}
}
Debug.WriteLine(string.Format("Initiated {0} Listeners from 8484 - {1}.", capacity, portStart));
}
public void EndAccept(IAsyncResult IAR)
{
TcpListener Listener = (TcpListener)IAR.AsyncState;
Socket socket = Listener.EndAcceptSocket(IAR);
frmMain.Clients.Add(clientCount, new Client(socket));
Listener.Stop();
Listener = null;
clientCount++;
frmMain.Instance.UpdateClients();
}
}
However, that doesn't work. The program crashes when accepting a new connection, why's that?
You're passing null as the "state" in BeginAcceptSocket, thus the error when you attempt to cast it back and then use it.
Try changing this line:
listener.BeginAcceptSocket(new AsyncCallback(EndAccept), null);
To:
listener.BeginAcceptSocket(new AsyncCallback(EndAccept), listener);
This is how i implement a Listener:
public class EasySocketListener : IDisposable
{
private Socket _socket;
public void Start(int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(new IPEndPoint(IPAddress.Any, port));
_socket.Listen(1);
StartAccepting();
}
private void StartAccepting()
{
try
{
_socket.BeginAccept((asyncResult) =>
{
try
{
Socket clientSocket = _socket.EndAccept(asyncResult);
if (OnSocketAccept != null)
OnSocketAccept(this, new SocketEventArgs(clientSocket));
StartAccepting();
}
catch { }
}, null);
}
catch { }
}
public void Dispose()
{
if (_socket != null)
{
_socket.Dispose();
_socket = null;
}
}
public event EventHandler<SocketEventArgs> OnSocketAccept;
}
This can accept multiple client sockets. When a client connects, the OnSocketAccept triggers.
Needs the SocketEventArgs:
public class SocketEventArgs : EventArgs
{
public Socket Socket { get; private set; }
public SocketEventArgs(Socket socket)
{
Socket = socket;
}
}
example:
private void Init()
{
_listener = new EasySocketListener();
_listener.OnSocketAccept += Listener_OnSocketAccept;
_listener.Start(port);
}
private void Listener_OnSocketAccept(object sender, SocketEventArgs e)
{
Debug.WriteLine( e.Socket.RemoteEndPoint );
}
This will come on my blog http://csharp.vanlangen.biz but haven't wrote it there yet. You can find some methods for reading asynchronous from a socket.

Out of memory exception on server, but most troubling; events not being called unless I debug

I have this very weird error. Basically, as soon as I add the line of code Connections.Add(handler); my program goes haywire. I'm also getting the error:
System.OutOfMemoryException: Exception of type
'System.OutOfMemoryException' was thrown. at
System.Threading.ExecutionContext.CreateCopy() at
System.Net.ContextAwareResult.CaptureOrComplete(ExecutionContext&
cachedContext, Boolean returnContext)
What happens is, when I add this code, connections are still being accepted, but nothing is being logged on my log richtextbox control. This is very weird, and I have no idea whats going on. However, removing that Connections.Add(handler) line in my accept event solves all problems. But I need to keep track of sockets somehow so I can implement pinging to keep them alive
Here is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Concurrent;
namespace SpybotServer
{
public partial class Server : Form
{
public void log(String text)
{
logs.InvokeEx(a => a.Text += (text +Environment.NewLine));
}
public Server()
{
InitializeComponent();
}
private void Server_Load(object sender, EventArgs e)
{
Thread serverThread = new Thread(delegate()
{
Listener.StartListening(9001);
});
serverThread.Start();
heartbeat.Start();
}
private void Server_FormClosed(object sender, FormClosedEventArgs e)
{
Listener.looping = false;
}
private void heartbeat_Tick(object sender, EventArgs e)
{
Listener.heartbeat();
}
}
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
public class Listener
{
public static Boolean looping = true;
private static List<Socket> Connections = new List<Socket>();
public static void heartbeat()
{
Program.MainForm.log("Sending ping...");
}
public static void StartListening(int port)
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 9001);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Program.MainForm.log("Listening on port " + port);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (looping)
{
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
}
}
catch (Exception e)
{
Program.MainForm.log(e.ToString());
}
}
public static void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
IPEndPoint ip = handler.RemoteEndPoint as IPEndPoint;
Program.MainForm.log("Accepted connection from " + ip.Address);
//Connections.Add(handler);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;
try
{
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
content = state.sb.ToString();
/*if (content.IndexOf("!#<EOF_END>#!") > -1)
{
Program.MainForm.log(content);
}
else
{
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}*/
}
}
catch (Exception e)
{
Program.MainForm.log(e.ToString());
}
}
private static void Send(Socket handler, String data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
Socket handler = (Socket)ar.AsyncState;
try
{
int bytesSent = handler.EndSend(ar);
if (bytesSent <= 0)
{
Program.MainForm.log("Socket has been closed.");
}
}
catch (Exception e)
{
Program.MainForm.log(e.ToString());
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
}
}
InvokeEx:
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace SpybotServer
{
static class ISynchronizeInvokeExtensions
{
public static void InvokeEx<T>(this T #this, Action<T> action) where T : ISynchronizeInvoke
{
if (#this.InvokeRequired)
{
#this.Invoke(action, new object[] { #this });
}
else
{
action(#this);
}
}
}
}
Since this callback:
public static void AcceptCallback(IAsyncResult ar)
is inside this loop:
while (looping)
{
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
}
I'm more than 90% certain that you are adding the same Socket to the Connections list over and over and just growing the size of the list at an alarming rate. Change the add to this:
if (Connections.Contains(handler))
{
Connections.Add(handler);
}
Michael is on the right track, but not with the right solution.
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
Is (unlike Accept) not going to block and weird things are going to happen if you call it this way. Instead take your BeginAccept out of a loop and call it again from AcceptCallback so that you can accept a new connection after you have accepted a first.

Categories

Resources