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
Related
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.
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) =>
I am writing a mono C# application that needs to use UDP. I was writing my test suite so that I could make sure packets are received properly with NUnit.
I made a minimal working example with a UdpCom class that is supposed to just listen right now and print out the bytes it receives in the call back method.
My minimal UdpCom class looks like:
using System;
using System.Net;
using System.Net.Sockets;
namespace UdpPractice
{
public class UdpState
{
public UdpClient client;
public IPEndPoint endpoint;
public UdpState(UdpClient c, IPEndPoint iep)
{
this.client = c;
this.endpoint = iep;
}
}
public class UdpCom
{
public UdpState uState;
public UdpClient uClient;
public IPAddress address;
public int port;
public IPEndPoint uEndpoint;
public UdpCom (IPAddress address, int port)
{
uEndpoint = new IPEndPoint (address, port);
uClient = new UdpClient (uEndpoint);
uState = new UdpState (uClient, uEndpoint);
uClient.BeginReceive (new AsyncCallback(RxCallback), uState);
}
public void RxCallback(IAsyncResult result)
{
UdpState rState = (UdpState)(result.AsyncState);
UdpClient rClient = rState.client;
IPEndPoint rEndPoint = rState.endpoint;
byte[] rxBytes = rClient.EndReceive (result, ref rEndPoint);
Console.WriteLine ("Received Bytes ___________________________");
Console.WriteLine (rxBytes.ToString ());
rClient.BeginReceive (new AsyncCallback(RxCallback), rState);
}
}
}
My simple test instantiates this class and then sends it a dummy packet of bytes. I am not testing the result right now, just placing a break point in my RxCallback method.
This is my NUNIT test:
using NUnit.Framework;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UdpPractice;
namespace UdpTest
{
[TestFixture ()]
public class Test
{
[Test ()]
public void TestCase ()
{
// Setup Receiver
IPAddress address = new IPAddress (new byte[] { 127, 0, 0, 1 });
int port = 14580;
UdpCom com = new UdpCom (address, port);
com.uClient.Connect (com.uEndpoint);
// Set up sender
UdpClient sender = new UdpClient(new IPEndPoint (address, port));
sender.Connect (address, port);
// Dummy Data
byte [] dummyData = new byte[] {1, 2, 3, 4, 4, 5};
sender.Send (dummyData, dummyData.Length);
Thread.Sleep (100);
// Close
sender.Close ();
com.uClient.Close ();
}
}
}
My Issue is that when I'm in the RxCallback method on the line that I'm trying to retrieve the bytes I am getting this exception:
System.ObjectDisposedException has been thrown
Cannot access a disposed object.
Object name: System.Net.Sockets.UdpClient
I want to be able to store these bytes in a queue in my UdpCom class but I am having trouble accessing them in the first place.
I may be failing to udner stand some basic UDP concepts as well here but it seems pretty straght forward.
The udp examples I have been following are:
https://yal.cc/cs-dotnet-asynchronous-udp-example/
https://www.codeproject.com/articles/132623/basic-udp-receiver
EDIT
I updated my class and tests as follows so I don't use the local loopback. But I am still getting the same exception.
UdpCom is now:
using System;
using System.Net;
using System.Net.Sockets;
namespace UdpPractice
{
public class UdpState
{
public UdpClient client;
public IPEndPoint endpoint;
public UdpState(UdpClient c, IPEndPoint iep)
{
this.client = c;
this.endpoint = iep;
}
}
public class UdpCom
{
public UdpState uState;
public UdpClient uClient;
public IPAddress address;
public int port;
public IPEndPoint uEndpoint;
public UdpCom (IPAddress address, int port)
{
uEndpoint = new IPEndPoint (address, port);
uClient = new UdpClient (uEndpoint);
uState = new UdpState (uClient, uEndpoint);
uClient.BeginReceive (new AsyncCallback(RxCallback), uState);
}
public void RxCallback(IAsyncResult result)
{
UdpState rState = (UdpState)(result.AsyncState);
UdpClient rClient = rState.client;
IPEndPoint rEndPoint = rState.endpoint;
byte[] rxBytes = rClient.EndReceive (result, ref rEndPoint);
Console.WriteLine ("Received Bytes ___________________________");
Console.WriteLine (rxBytes.ToString ());
rClient.BeginReceive (new AsyncCallback(RxCallback), rState);
}
}
}
and the test is:
using NUnit.Framework;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UdpPractice;
namespace UdpTest
{
[TestFixture ()]
public class Test
{
[Test ()]
public void TestCase ()
{
// Setup Receiver
IPAddress address = new IPAddress (new byte[] { 192, 168, 1, 161 });
int port = 14580;
UdpCom com = new UdpCom (IPAddress.Any, port);
// com.uClient.Connect (com.uEndpoint);
// Set up sender
UdpClient sender = new UdpClient(new IPEndPoint (address, port));
sender.Connect (address, port);
// Dummy Data
byte [] dummyData = new byte[] {1, 2, 3, 4, 4, 5};
sender.Send (dummyData, dummyData.Length);
Thread.Sleep (100);
// Close
sender.Close ();
com.uClient.Close ();
}
}
}
I guess I was struggling with a basic misunderstanding with how to communicate with UDP.
UdpCom:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
namespace UdpPractice
{
public class UdpState
{
public UdpClient client;
public IPEndPoint endpoint;
public UdpState(UdpClient c, IPEndPoint iep)
{
this.client = c;
this.endpoint = iep;
}
}
public class UdpCom
{
public UdpState uState;
public IPAddress address;
public int port;
public IPEndPoint uEndpoint;
public bool receiveFlag;
public List<byte[]> rxBytesBuffer;
public UdpCom (IPAddress address, int port)
{
uEndpoint = new IPEndPoint (address, port);
// uClient = new UdpClient (uEndpoint);
uState = new UdpState (new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port)), uEndpoint);
receiveFlag = false;
uState.client.BeginReceive (new AsyncCallback(RxCallback), uState);
rxBytesBuffer = new List<byte[]> ();
}
public void RxCallback(IAsyncResult result)
{
UdpState rState = (UdpState)result.AsyncState;
UdpClient rClient = ((UdpState)result.AsyncState).client;
IPEndPoint rEndPoint = ((UdpState)result.AsyncState).endpoint;
byte[] rxBytes = rClient.EndReceive (result, ref rEndPoint);
rxBytesBuffer.Add (rxBytes);
Console.WriteLine ("Received Bytes ___________________________");
Console.WriteLine (rxBytes.ToString ());
receiveFlag = true;
rClient.BeginReceive (new AsyncCallback(RxCallback), result.AsyncState);
}
}
}
Test:
using NUnit.Framework;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UdpPractice;
namespace UdpTest
{
[TestFixture ()]
public class Test
{
[Test ()]
public void TestCase ()
{
// Setup Listener
int port = 14580;
IPEndPoint locep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
// Server (Listener)
UdpCom com = new UdpCom (IPAddress.Any, port);
// Set up sender
UdpClient sender = new UdpClient();
// Dummy Data
byte [] dummyData = new byte[] {1, 2, 3, 4, 4, 5};
sender.Send (dummyData, dummyData.Length, locep);
sender.Send (dummyData, dummyData.Length, locep);
Thread.Sleep (100);
Assert.AreEqual(true, com.receiveFlag);
}
}
}
I needed to make the listener listen to IPAddress.Any and then I mainly used the Send method with the EndPoint argument. I had to add the delay in there because otherwise the receive flag wasn't being set.
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.
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!