Asynchronous SSL Socket - c#

Recently I was creating an asynchronous ssl socket class. I finished it, and it authenticated with the client successfully but it did not receive the message sent by client correctly.
Here is my 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.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.IO;
public class Wrapper
{
public byte[] buffer;
public SslStream sslStream;
public object connector;
}
public class Sock
{
private Dictionary<string, byte> Connections;
public event Action<Wrapper> AnnounceNewConnection;
public event Action<Wrapper> AnnounceDisconnection;
public event Action<byte[], Wrapper> AnnounceReceive;
private Socket _sock;
private X509Certificate certificate = X509Certificate.CreateFromCertFile("exportedcertificate.cer");
public Sock(int port)
{
try
{
Connections = new Dictionary<string, byte>();
_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_sock.Bind(new IPEndPoint(IPAddress.Any, port));
_sock.Listen(500);
_sock.BeginAccept(AcceptConnections, new Wrapper());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private void AcceptConnections(IAsyncResult result)
{
Wrapper wr = (Wrapper)result.AsyncState;
try
{
wr.sslStream = new SslStream(new NetworkStream(_sock.EndAccept(result), true));
wr.sslStream.BeginAuthenticateAsServer(certificate, EndAuthenticate, wr);
_sock.BeginAccept(AcceptConnections, new Wrapper());
}
catch (Exception e) { Console.WriteLine(e); }
}
private void EndAuthenticate(IAsyncResult result)
{
Wrapper wr = (Wrapper)result.AsyncState;
try
{
wr.sslStream.EndAuthenticateAsServer(result);
if (wr.sslStream.IsAuthenticated == true)
{
wr.buffer = new byte[65535];
wr.sslStream.BeginRead(wr.buffer, 0, wr.buffer.Length, ReceiveData, wr);
AnnounceNewConnection.Invoke(wr);
}
}
catch (Exception e) { Console.WriteLine(e); }
}
private void ReceiveData(IAsyncResult result)
{
Wrapper wr = (Wrapper)result.AsyncState;
try
{
int size = wr.sslStream.EndRead(result);
byte[] buffer = new byte[size];
Buffer.BlockCopy(wr.buffer, 0, buffer, 0, size);
AnnounceReceive.Invoke(wr.buffer, wr);
if (wr.sslStream.IsAuthenticated)
wr.sslStream.BeginRead(wr.buffer, 0, wr.buffer.Length, ReceiveData, wr);
}
catch (Exception e) { Console.WriteLine(e); AnnounceDisconnection.Invoke(wr); }
}
}
So in the code above when I call BeginRead and try to use
Console.WriteLine(Encoding.ASCII.GetString(arg1));,
I only get alot of empty lines [Note I use the ssl client from the MSDN example to test my server]
I really want to know why it does not correctly receive the message!

Related

Why doesn't my udp client throw an exception when I try to receive data in the method RecData()?

It's for a multiplayer video game:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace ShootingMasters
{
public class Communicator
{
public UdpClient client;
public IPAddress toconnectto;
public Communicator(IPAddress toconnectto)
{
this.toconnectto = toconnectto;
client = new UdpClient();
client.Connect(toconnectto, 25565);
}
public void SendData(string data)
{
byte[] bdata = ASCIIEncoding.ASCII.GetBytes(data);
IPEndPoint iP = new IPEndPoint(toconnectto, 25565);
try
{
client.Send(bdata, bdata.Length);
}
catch(Exception e)
{
}
}
public string RecData()
{
if (client.Available > 0)
{
try
{
IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 25565);
byte[] data = client.Receive(ref iPEndPoint);
return ASCIIEncoding.ASCII.GetString(data);
}
catch(Exception e)
{
return null;
}
}
else
{
return null;
}
}
}
}
When you call receive, it returns null because an exception was thrown. The exception message was
An existing connection was forcibly closed by the remote host
Also, inside receive client.Available is 1 then right after an exception is thrown, it is 0.

C# Tcp Async Programming

I try to learn and wrote some code for TCP connection.
This is my Server Class :
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Tcp
{
public class Server
{
#region Constructor
public Server()
{
}
#endregion
#region Field
//Server Socket
public Socket SrvSocket;
//Server Port
private int _socketPort = 8080;
byte[] byteData = new byte[1024];
#endregion
#region Properties
/// <summary>
/// Socket Port Int Value
/// </summary>
public int SocketPort
{
get
{
return _socketPort;
}
set
{
_socketPort = value;
}
}
#endregion
#region Method
public void Close()
{
SrvSocket.Shutdown(SocketShutdown.Both);
}
/// <summary>
/// Open TCP Socket
/// </summary>
public void Connect()
{
try
{
SrvSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any,_socketPort);
SrvSocket.Bind(ipEndPoint);
SrvSocket.Listen(4);
SrvSocket.BeginAccept(new AsyncCallback(OnAccept), null); //TODO : تست کنم State را یک بار سوکت بگذارم یکبار State خودم
}
catch (SocketException ex)
{
MessageBox.Show(#"Socket Exception trown : " + ex.Message);
}
catch (TimeoutException ex)
{
MessageBox.Show(#"Timeout Exception trown : " + ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(#"Exception trown : " + ex.Message);
}
}
public void OnAccept(IAsyncResult ar)
{
try
{
Socket ClntSocket = SrvSocket.EndAccept(ar); // روند تایید انجام شد.
SrvSocket.BeginAccept(new AsyncCallback(OnAccept), null); // ممکنه کلاینت های دیگه هم بخواند وصل بشند
//SocketState state = new SocketState(); // وضعیت پورت تنظیم میکنیم
ClntSocket.BeginReceive(byteData, 0, byteData.Length
, SocketFlags.None,new AsyncCallback(OnReceive), ClntSocket); // شروع به دریافت میکنیم
}
catch (Exception ex)
{
MessageBox.Show(#"On Accept Exception trown : " + ex.Message);
}
}
#endregion
public void OnReceive(IAsyncResult ar)
{
try
{
Socket ClntSocket = (Socket)ar.AsyncState;
int byteReades = ClntSocket.EndReceive(ar);
if (byteReades > 0)
{
var collectedData = Encoding.ASCII.GetString(byteData, 0, byteReades);
Console.WriteLine(collectedData);
}
ClntSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), ClntSocket);
}
catch (Exception ex)
{
MessageBox.Show(#"On receive Exception trown : " + ex.Message);
}
}
public void Send(string data)
{
//var sendData = Encoding.ASCII.GetBytes(data);
//IPEndPoint ConToSocket = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 8080);
//TcpClient Client = new TcpClient(ConToSocket);
//Client.
}
public void OnSend(IAsyncResult ar)
{
}
}
public class SocketState
{
public Socket TransferSocket = null;
/// <summary>
/// Buffer Size
/// </summary>
public const int bufferSize = 1024;
/// <summary>
/// Recieved byte
/// </summary>
public byte[] buffer = new byte[bufferSize];
/// <summary>
/// Offset
/// </summary>
public int offset = 0;
}
}
First question: Why can I only connect to the server once?
I use telnet to connect server on local pc.when i open more telnet no stop all sending !
And this is my Client Class :
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.Windows.Forms;
namespace Tcp
{
class Client
{
Socket ClientSocket = null;
public void Connect(string RemoteIp, int RemotePort)
{
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint RemoteSrv = new IPEndPoint(IPAddress.Parse(RemoteIp), RemotePort);
ClientSocket.BeginConnect(RemoteSrv, new AsyncCallback(OnConnect), null);
}
public void OnConnect(IAsyncResult ar)
{
try
{
ClientSocket.EndConnect(ar);
}
catch (Exception ex)
{
MessageBox.Show("Exp Thrown OnConnect : " + ex.Message);
}
}
public void Send(string str)
{
byte[] data = Encoding.ASCII.GetBytes(str);
ClientSocket.BeginSend(data,0,data.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
}
public void OnSend(IAsyncResult ar)
{
try
{
ClientSocket.EndSend(ar);
}
catch (Exception ex )
{
MessageBox.Show("Exp Thrown OnSend : " + ex.Message);
}
}
}
}
When i Connect to server and see socket state in break point connected socket is not 8080 ! Is it wrong ?
And server can not return received data in Console.Writeline , Where is my issue ?
var collectedData = Encoding.ASCII.GetString(byteData, 0, byteReades);
Console.WriteLine(collectedData);
Why i can not Receive form my Client Class !
Finally i need solution to know best way to Send/Receive Communication between my computer and Device via TCP async.
Thank you.

sending data using udp

i am using those scripts bellow to send and receive data, when i send data from an android support to my computer i can't receive anything !!! i can't find the problem can anyone help me please
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UDPSend : MonoBehaviour
{
public string IP = "myIP"; // default local
public int port = 26000;
IPEndPoint remoteEndPoint;
UdpClient client;
string strMessage="";
public void Start()
{
init();
}
void OnGUI()
{
Rect rectObj=new Rect(40,380,200,400);
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.UpperLeft;
GUI.Box(rectObj,"UDPSendData\n IP : "+IP+" Port : "+port,style);
//
strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
if (GUI.Button(new Rect(190,420,40,20),"Send"))
{
sendString(strMessage+"\n");
}
}
// init
public void init()
{
IP="myIP";
port=26000; // quake port ;)
remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
//remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, port); // toute machine
client = new UdpClient();
}
// sendData
private void sendString(string message)
{
try
{
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
print(err.ToString());
}
}
void OnDisable()
{
if ( client!= null) client.Close();
}
}
UDPReceive:
using UnityEngine;
using System.Collections;
using System;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net.NetworkInformation;
public class UDPReceive : MonoBehaviour {
Thread receiveThread;
UdpClient client;
public int port = 26000;
string strReceiveUDP="";
string LocalIP = String.Empty;
string hostname;
public void Start()
{
Application.runInBackground = true;
init();
}
// init
private void init()
{
receiveThread = new Thread( new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
hostname = Dns.GetHostName();
IPAddress[] ips = Dns.GetHostAddresses(hostname);
if (ips.Length > 0)
{
LocalIP = ips[0].ToString();
}
}
void OnGUI()
{
Rect rectObj=new Rect(10,10,400,200);
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.UpperLeft;
GUI.Box(rectObj,hostname+" MY IP : "+LocalIP+" : "+strReceiveUDP,style);
}
private void ReceiveData()
{
client = new UdpClient(port);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Broadcast, port);
//IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.UTF8.GetString(data);
strReceiveUDP = text;
//Debug.Log(strReceiveUDP);
}
catch (Exception err)
{
print(err.ToString());
}
}
}
public string UDPGetPacket()
{
return strReceiveUDP;
}
void OnDisable()
{
if ( receiveThread!= null) receiveThread.Abort();
client.Close();
}
}
When myIP is 127.0.0.1 everything works normally

named pipe client won't work in unity3d

I wrote this C# code to have namedPipeServer and NamedPipeClient, with Asynchronous read and write settings, connect to each other. Both code runs perfectly on visual studio 2010 that I am using with read and write working well without any application freeze during runtime.
But I want the client side running in unity3d. The problem I encounter is in client side code implemented in Unity3D. When I use Write_to_Server_Async(string message), read in the server side is not invoked and is only invoked when I quit Unity3d (I have end its process typically). I can tell something wrong with Unity3D, because the exact code works perfectly in visual studio, so I know my code is implemented the right way. I have heard about how unity3d does not really use real threads unless user manually creates one but even that has not solved the problem. My speculation is Unity3D developers might have created their version of .NET library 3.5 (sounds bizzare (does explain why they still haven't adopted 4.5)) or somehow they must have structured their library in a way that by default functions like NamedPipeClientStream.BeginWrite cannot create its own real thread. But then again I am not sure if its the problem with threads.
At the moment, I would like anyone to come up with good explanation.
Make sure to replace Debug.WriteLine to UnityEngine.Debug.Log in unity3d.
Below is Client Main method code and class
class PipeClient
{
private static Asynchronus_NamedPipe_Client client;
static void Main(string[] args)
{
client = new Asynchronus_NamedPipe_Client("mypipe7055");
while (client.Is_connected_to_server()) {
if (Console.ReadKey().Key == ConsoleKey.T)
{
client.Write_to_Server_Async("NEX CLIENT");
}
}
}
}
Asynchronus_NamedPipe_Client class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Security.Principal;
using System.Diagnostics;
using System.Threading;
namespace NamedPipes_CLIENT
{
public class Asynchronus_NamedPipe_Client
{
public readonly string pipe_address;
private System.IO.Pipes.NamedPipeClientStream clientStream;
public bool filter_message = true;
private string Server_Message = null;
public event ASYNC_pipe_status_callback ASYNC_external_Write_Completed;
public event ASYNC_pipe_status_callback ASYNC_external_Read_Completed;
public delegate void ASYNC_pipe_status_callback(string message);
private byte[] read_buffer = new byte[1024];
private byte[] write_buffer = new byte[1024];
private IAsyncResult read_result;
private IAsyncResult write_result;
private int read_id = 1;
public Asynchronus_NamedPipe_Client(string pipe_address)
{
try
{
this.pipe_address = pipe_address;
// if(clientStream.IsConnected){UnityEngine.Debug.Log("Server Already Running");}else{}
clientStream = new NamedPipeClientStream(".", this.pipe_address, PipeDirection.InOut, PipeOptions.Asynchronous);
clientStream.Connect(1);
if (clientStream.IsConnected)
{
Console.WriteLine("Connected to Server");
Read_from_Server_Async();
}
else { Console.WriteLine("Could NOT connect to Server"); }
}
catch (Exception oEX) { Console.WriteLine("Application Pipe Error: "+oEX.Message); }
}
public void Write_to_Server_Async(string message)
{
if (clientStream != null)
{
if (clientStream.CanWrite && clientStream.IsConnected)
{
clientStream.WaitForPipeDrain();
ASCIIEncoding.ASCII.GetBytes(message).CopyTo(write_buffer,0);
clientStream.BeginWrite(write_buffer, 0, write_buffer.Length, new AsyncCallback(Async_Write_Completed), 1);
} else { close_pipe(); }
}
}
public void Read_from_Server_Async()
{
if (clientStream.CanRead && clientStream.IsConnected)
{
clientStream.BeginRead(read_buffer, 0, read_buffer.Length, new AsyncCallback(Async_Read_Completed), 2);
} else { close_pipe(); }
}
private void Async_Write_Completed(IAsyncResult result)
{
clientStream.EndWrite(result);
Debug.WriteLine("Written To Server => " + ASCIIEncoding.ASCII.GetString(write_buffer));
// close_pipe();
}
private void Async_Read_Completed(IAsyncResult result)
{
clientStream.EndRead(result);
Server_Message = ASCIIEncoding.ASCII.GetString(read_buffer);
this.Server_Message.Trim();
Console.WriteLine("Received from Server => " + Server_Message);
Debug.WriteLine("Received from Server => " + Server_Message);
if (clientStream.CanRead && clientStream.IsConnected)
{
Read_from_Server_Async();
}
else { close_pipe(); }
}
public Boolean Is_connected_to_server() {
return clientStream.IsConnected;
}
public void close_pipe()
{
if (clientStream != null)
{
if (clientStream.IsConnected)
{
clientStream.Close();
clientStream.Dispose();
Debug.WriteLine(" Pipe Closed");
}
}
}
}
}
Server side Main method implementation
static void Main(string[] args)
{
Asynchronus_NamedPipe_Server Async_server = new Asynchronus_NamedPipe_Server("mypipe7055");
while (true)
{
do
{
Async_server.Write_to_Client_Async("yeye");
Console.WriteLine("escape key");
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
}
Server Side Class -----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
using System.IO;
using System.ComponentModel;
using System.Diagnostics;
namespace Application_Pipe
{
public class Asynchronus_NamedPipe_Server
{
public readonly string pipe_address;
private System.IO.Pipes.NamedPipeServerStream namedPipeServerStream;
private string Server_Message;
public delegate void ASYNC_pipe_status_callback(string message);
private byte[] read_buffer = new byte[1024];
private byte[] write_buffer = new byte[1024];
public Asynchronus_NamedPipe_Server(string pipe_address)
{
try
{
this.pipe_address = pipe_address;
namedPipeServerStream = new NamedPipeServerStream(this.pipe_address,
PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); //new NamedPipeServerStream(pipe_address);
Console.WriteLine("Connecting to Client...");
namedPipeServerStream.WaitForConnection();
Console.WriteLine("Connected to Client");
Read_from_Client_Async();
}
catch (Exception oEX) { Console.WriteLine(oEX.Message); }
}
public void Write_to_Client_Async(string message)
{
if (namedPipeServerStream != null)
{
if (namedPipeServerStream.CanWrite && namedPipeServerStream.IsConnected)
{
namedPipeServerStream.WaitForPipeDrain();
ASCIIEncoding.ASCII.GetBytes(message).CopyTo(write_buffer,0);
namedPipeServerStream.BeginWrite(write_buffer, 0, write_buffer.Length, new AsyncCallback(Async_Write_Completed), 2);
}
else { close_pipe(); }
}
}
public void Read_from_Client_Async()
{
if (namedPipeServerStream != null)
{
if (namedPipeServerStream.CanRead && namedPipeServerStream.IsConnected)
{
namedPipeServerStream.BeginRead(read_buffer, 0, read_buffer.Length, new AsyncCallback(Async_Read_Completed), 1);
} else { close_pipe(); }
}
}
private void Async_Read_Completed(IAsyncResult result)
{
namedPipeServerStream.EndRead(result);
this.Server_Message = ASCIIEncoding.ASCII.GetString(read_buffer);
this.Server_Message.Trim();
Debug.WriteLine("Received from Client => " + this.Server_Message+" <=REnd");
Read_from_Client_Async();
}
private void Async_Write_Completed(IAsyncResult result)
{
namedPipeServerStream.EndWrite(result);
Debug.WriteLine("Written To Client => " + ASCIIEncoding.ASCII.GetString(write_buffer));
}
public Boolean Is_connected_to_server()
{
return this.namedPipeServerStream.IsConnected;
}
public void close_pipe()
{
if(namedPipeServerStream.IsConnected){
namedPipeServerStream.Disconnect();
}
namedPipeServerStream.Close();
namedPipeServerStream.Dispose();
Debug.WriteLine(" Pipe Closed");
}
} //------class End
}

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