TCP Socket Client\Server Request Response - c#

I'm developing a .Net 4.5.2 windows TCP socket master\client messaging solution. The solution is working for the most part; however I need the server to send a response message back to the client when the send button is selected. When the connect button is selected the master does successfully send a response message back to the client. I have made numerous attempts to send the response message back to the client application from the master when the send button is selected, but I have been unable to make it work. I am looking for some help to get me moving forward again. Don’t want to keep spinning my wheels and making no progress. Thanks in advance for the help. Please find below the server and client solutions:
Server Code:
public partial class ServerForm : Form
{
private Socket serverSocket;
private Socket clientSocket; // We will only accept one socket.
private byte[] buffer;
public ServerForm()
{
InitializeComponent();
StartServer();
}
private static void ShowErrorDialog(string message)
{
MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void StartServer()
{
try
{
IPAddress ipAddress = IPAddress.Parse("192.168.1.124");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ipAddress, 4545));
serverSocket.Listen(10);
serverSocket.BeginAccept(AcceptCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void AcceptCallback(IAsyncResult AR)
{
try
{
clientSocket = serverSocket.EndAccept(AR);
buffer = new byte[clientSocket.ReceiveBufferSize];
var sendData = Encoding.ASCII.GetBytes("Hello");
clientSocket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, SendCallback, null);
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
serverSocket.BeginAccept(AcceptCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void SendCallback(IAsyncResult AR)
{
try
{
clientSocket.EndSend(AR);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void ReceiveCallback(IAsyncResult AR)
{
try
{
Socket current = (Socket)AR.AsyncState;
int received = clientSocket.EndReceive(AR);
if (received == 0)
{
return;
}
PersonPackage person = new PersonPackage(buffer);
SubmitPersonToDataGrid(person);
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
//Added BeginSend which answered my question. Simple enough fix. Thanks for looking...
byte[] sendData = Encoding.ASCII.GetBytes(person.Name);
clientSocket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, SendCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
Client Code:
public partial class ClientForm : Form
{
private Socket clientSocket;
private byte[] buffer;
public ClientForm()
{
InitializeComponent();
}
private static void ShowErrorDialog(string message)
{
MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void ReceiveCallback(IAsyncResult AR)
{
try
{
int received = clientSocket.EndReceive(AR);
if (received == 0)
{
return;
}
string message = Encoding.ASCII.GetString(buffer).TrimEnd('\0');
Invoke((Action) delegate
{
textBoxEmployee.Text = string.Empty;
textBoxEmployee.Text = "Server says: " + message + " Paul";
});
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void ConnectCallback(IAsyncResult AR)
{
try
{
clientSocket.EndConnect(AR);
UpdateControlStates(true);
buffer = new byte[clientSocket.ReceiveBufferSize];
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void SendCallback(IAsyncResult AR)
{
try
{
clientSocket.EndSend(AR);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void UpdateControlStates(bool toggle)
{
Invoke((Action)delegate
{
buttonSend.Enabled = toggle;
buttonConnect.Enabled = !toggle;
labelIP.Visible = textBoxAddress.Visible = !toggle;
});
}
private void buttonSend_Click(object sender, EventArgs e)
{
try
{
PersonPackage person = new PersonPackage(checkBoxMale.Checked, (ushort)numberBoxAge.Value, textBoxEmployee.Text);
byte[] buffer = person.ToByteArray();
clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, SendCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
UpdateControlStates(false);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
UpdateControlStates(false);
}
}
private void buttonConnect_Click(object sender, EventArgs e)
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the specified host.
var endPoint = new IPEndPoint(IPAddress.Parse(textBoxAddress.Text), 4545);
clientSocket.BeginConnect(endPoint, ConnectCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
}

Found issue. Added BeginSend to server SendCallBack method. Code has been updated and works...

Related

Android socket connection with a server

I'm trying to connect my Android phone with a Server. On the Server runs a program written in C#. I've tryed to make it with the following code but it doesn't work.
This is the Android code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Socket socket;
int port = 52301;
String ip = "79.16.115.30";
Button b = (Button) findViewById(R.id.myButton);
assert b != null;
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
byte[] b = ip.getBytes();
/*SocketAddress socketAddress = new InetSocketAddress(ip, port);
socket.connect(socketAddress);*/
socket = new Socket(ip, port);
Toast.makeText(v.getContext(), "CONNESSO", Toast.LENGTH_SHORT).show();
} catch (UnknownHostException e) {
Toast.makeText(v.getContext(), "CHI MINCHIA è COSTUI", Toast.LENGTH_SHORT).show();
}catch(IOException e) {
Toast.makeText(v.getContext(), "NO I/O", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
String cause = "Message: " + e.getMessage();
Toast.makeText(v.getContext(), cause, Toast.LENGTH_SHORT).show();
}
}
});
}
I've tryed also to use the code commented but it doesn't work;
This is the program that runs on the Server:
static void Main(string[] args)
{
string ip = Get_external_ip();
int port = 52301;
int max = 10;
IPAddress ipAddress = IPAddress.Parse("192.168.1.56");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); //setto i parametri del socket
Socket sockServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //creo il socket
Socket client;
Console.WriteLine(ip);
try
{
sockServer.Bind(localEndPoint);
sockServer.Listen(max);
while (true)
{
client = sockServer.Accept();
Console.WriteLine(client.RemoteEndPoint.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
private static string Get_external_ip()
{
try
{
WebClient client = new WebClient();
return client.DownloadString("http://icanhazip.com/").TrimEnd('\r', '\n');
}
catch (Exception e)
{
return e.Message;
}
}
First of all, use background Thread for network.
I will give you my working snippet. Try to apply it for your needs.
public class YourClass {
//Server socket variables
private ServerSocket serverSocket;
private DataOutputStream dataOutputStream;
private DataInputStream dataInputStream;
private Socket client;
....
private class SocketServerThread extends Thread {
private int port;
private SocketServerThread(int port) {
this.port = port;
}
#Override
public void run() {
dataInputStream = null;
dataOutputStream = null;
try {
serverSocket = new ServerSocket(port);
isSockedOpened = true;
client = serverSocket.accept(); //wait for client
isClientConnected = true;
Log.d(TAG, "Client connected: " + client.getInetAddress().getHostAddress());
dataInputStream = new DataInputStream(
client.getInputStream());
dataOutputStream = new DataOutputStream(
client.getOutputStream());
String messageFromClient;
while (isClientConnected) {
messageFromClient = dataInputStream.readLine();
handleIncomingMessage(messageFromClient);
}
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage());
}
}
}
To open connection:
public void connect(int port) {
this.port = port;
Thread socketServerThread = new Thread(new SocketServerThread(port));
socketServerThread.start();
}
That's how you check if client connected;
public boolean isConnected() {
return serverSocket.isBound() || client.isConnected();
}
To disconnect:
public void disconnect(boolean needsGathering) {
if (isSockedOpened) {
try {
if (serverSocket != null) {
serverSocket.close();
}
if (dataOutputStream != null) {
dataOutputStream.close();
}
if (dataInputStream != null) {
dataInputStream.close();
}
if (client != null) {
client.close();
}
} catch (IOException e) {
Log.e(TAG, "Couldn't get I/O for the connection");
Log.e(TAG, e.getMessage());
}
} else {
Log.d(TAG, "Socket was not opened");
}
}
}

Android Video Streaming Using DatagramSocket setPreviewCallback

I've made an application that obeys UDP using Datagram Socket in android. I'm trying to use Camera's setPreviewCallback function to send bytes to a (c#) client, using Datagram Socket;
But,
The problem is : it throws an exception "The datagram was too big to fit the specified buffer,so truncated" and no bytes are received on client.
I've changed the size of buffer to different values but none work. Now :
Is Datagram approach is right?
What alternatives/approach I'd use to achieve the task?
What's the ideal solution for this?
Android Server :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = (VideoView) findViewById(R.id.videoView1);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
setTitle(GetCurrentIP());
mainList = new LinkedList<byte[]>();
secondaryList = new LinkedList<byte[]>();
mCam = null;
mCam = Camera.open();
if (mCam == null) {
Msg("Camera is null");
} else {
if (!Bind()) {
Msg("Bind Error.");
} else {
Msg("Bound Success.");
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mCam.setPreviewDisplay(videoView.getHolder());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Msg(e1.getMessage());
}
mCam.setPreviewCallback(new PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO Auto-generated method stub
DatagramPacket pack;
try {
pack = new DatagramPacket(data, data.length, InetAddress.getByName(clientIP), clientPort);
me.send(pack);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msg(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msg(e.getMessage());
}
}
});
mCam.startPreview();
}
});
}
}
}
private boolean Bind(){
try {
me = new DatagramSocket(MY_PORT);
return true;
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Msg(e.getMessage());
}
return false;
}
private String GetCurrentIP(){
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
return Formatter.formatIpAddress(wifiMgr.getConnectionInfo().getIpAddress());
}
public void Msg(String msg){
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
Log.v(">>>>>", msg);
}
}
C# client :
public partial class Form1 : Form
{
const int MY_PORT = 55566;
IPAddress MY_IP;
Thread Receiver;
Socket me;
EndPoint myEndPoint;
EndPoint serverEndPoint;
byte[] buffer;
public Form1()
{
InitializeComponent();
}
private IPAddress GetCurrentIPAddress()
{
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
var selectedIPs = from ip in ips
where ip.AddressFamily == AddressFamily.InterNetwork
select ip;
return selectedIPs.First();
}
private bool Bind()
{
try
{
myEndPoint = new IPEndPoint(MY_IP, MY_PORT);
me.Bind(myEndPoint);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
MY_IP = GetCurrentIPAddress();
this.Text = MY_IP.ToString()+":"+MY_PORT;
me = new Socket
(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp
);
if (!Bind())
Task.Run(()=> MessageBox.Show("Bind() error."));
else
Task.Run(() => MessageBox.Show("Bind success."));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//private void AddToListBox(String msg)
//{
// this.Invoke((Action)delegate() { this.listBox1.Items.Add((this.listBox1.Items.Count+1)+" : "+msg); });
//}
private void buttonStart_Click(object sender, EventArgs e)
{
serverEndPoint = new IPEndPoint(IPAddress.Parse(textBoxmyIP.Text), int.Parse(textBoxmyPort.Text));
Receiver = new Thread(new ThreadStart(Receive));
Receiver.Start();
}
private Image ByteToImage(byte[] bytes)
{
MemoryStream ms = new MemoryStream(bytes);
return Image.FromStream(ms);
}
private void Receive()
{
while (true)
{
buffer = new byte[100];
int nobs = me.ReceiveFrom(buffer, ref serverEndPoint);
if (nobs>0)
{
Task.Run(() => MessageBox.Show("Bytes received"));
//AddToListBox(Encoding.Default.GetString(buffer));
//AddToPictureBox(buffer);
}
Thread.Sleep(100);
}
}
private void AddToPictureBox(byte[] buffer)
{
this.BeginInvoke
(
(Action)
delegate()
{
pictureBox1.Image = ByteToImage(buffer);
}
);
}
}

C# Form. Changing a Client / Server chat room so clients can speak with one another

This question has probably been asked before.
Okay so I am still learning how to program with sockets but I was wondering how you could change the client / server so that clients can talk amongst themselves as well as the server talking to the clients like an administrator.
I have found various things on Handle Clients but these were for Console Apps and not C# Windows Forms, I tried to covert them but with no luck.
This is my server code so far.
namespace Socket_Server
{
public partial class Form1 : Form
{
const int MAX_CLIENTS = 30;
public AsyncCallback pfnWorkerCallBack;
private Socket m_mainSocket;
private Socket[] m_workerSocket = new Socket[30];
private int m_clientCount = 20;
string readData = null;
public Form1()
{
InitializeComponent();
textBoxIP.Text = GetIP();
}
private void buttonStartListen_Click(object sender, EventArgs e)
{
try
{
if (textBoxPort.Text == "")
{
MessageBox.Show("Please enter a Port Number");
return;
}
string portStr = textBoxPort.Text;
int port = System.Convert.ToInt32(portStr);.
m_mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
m_mainSocket.Bind(ipLocal);
m_mainSocket.Listen(4);
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
UpdateControls(true);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
private void UpdateControls(bool listening)
{
buttonStartListen.Enabled = !listening;
buttonStopListen.Enabled = listening;
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
WaitForData(m_workerSocket[m_clientCount]);
++m_clientCount;
String str = String.Format("Client # {0} connected", m_clientCount);
Invoke(new Action(() =>textBoxMsg.Clear()));
Invoke(new Action(() =>textBoxMsg.AppendText(str)));
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public class SocketPacket
{
public System.Net.Sockets.Socket m_currentSocket;
public byte[] dataBuffer = new byte[1024];
}
public void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket();
theSocPkt.m_currentSocket = soc;// could be this one!!!
soc.BeginReceive(theSocPkt.dataBuffer, 0,
theSocPkt.dataBuffer.Length,
SocketFlags.None,
pfnWorkerCallBack,
theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;
iRx = socketData.m_currentSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(socketData.dataBuffer,
0, iRx, chars, 0);
System.String szData = new System.String(chars);
Invoke(new Action(() => richTextBoxSendMsg.AppendText(szData)));
Invoke(new Action(() => richTextBoxSendMsg.AppendText(Environment.NewLine)));
WaitForData(socketData.m_currentSocket);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
private void buttonSendMsg_Click(object sender, EventArgs e)
{
try
{
Object objData = txtBoxType.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
for (int i = 0; i < m_clientCount; i++)
{
if (m_workerSocket[i] != null)
{
if (m_workerSocket[i].Connected)
{
m_workerSocket[i].Send(byData);
txtBoxType.Clear();
}
}
}
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
private void buttonStopListen_Click(object sender, EventArgs e)
{
CloseSockets();
UpdateControls(false);
}
String GetIP()
{
String strHostName = Dns.GetHostName();
IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
String IPStr = "";
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
if (ipaddress.IsIPv6LinkLocal == false)
{
IPStr = IPStr + ipaddress.ToString();
return IPStr;
}
}
return IPStr;
}
private void buttonClose_Click(object sender, EventArgs e)
{
CloseSockets();
Close();
}
void CloseSockets()
{
if (m_mainSocket != null)
{
m_mainSocket.Close();
}
for (int i = 0; i < m_clientCount; i++)
{
if (m_workerSocket[i] != null)
{
m_workerSocket[i].Close();
m_workerSocket[i] = null;
}
}
}
}
}
Thank you in advance.

Getting a message of asynchronous GetReceiveData method

I have in MainPage:
private void AcceptCallBack(IAsyncResult ar)
{
try
{
((Service1)ar.AsyncState).EndAccept(ar);
}
catch
{
}
}
And in service1:
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
if (buffer != null)
{...
string str = System.Text.UTF8Encoding.UTF8.GetString(buffer);
strReceive = str;
}
worker.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new
AsyncCallback(ReceiveCallBack), worker);
}
catch (SocketException)
{
}
}
[OperationContract]
public void Accept(string Ip,int Port)
{
try
{
bind and listen....
}
catch
{
}
}
private void AcceptCallback(IAsyncResult ar)
{
try
{
...
worker.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new
AsyncCallback(ReceiveCallBack), worker);
}
catch (SocketException)
{
}
}
[OperationContract]
public string GetReceiveData()
{
return strReceive;
}
In MainPage, I would like to get message of GetReceiveData but I don't know how.

Asynchronous TCP socket not working in C#

I keep getting this error:
"The IAsyncResult object was not returned from the corresponding asynchonous method on this class. Parameter name : aysncResult. Line 105.
This happens when I attempt to connect to a local server; It errors and won't connect.
Here's my client code:
public class Client
{
public delegate void OnConnectEventHandler(Client sender, bool connected);
public event OnConnectEventHandler OnConnect;
public delegate void OnSendEventHandler(Client sender, int sent);
public event OnSendEventHandler OnSend;
public delegate void OnDisconnectEventHandler(Client sender);
public event OnDisconnectEventHandler OnDisconnect;
Socket socket;
public bool Connected
{
get
{
if (socket != null)
{
return socket.Connected;
}
return false;
}
}
public Client()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void SendData()
{
}
public void Connect(string IP, int port)
{
if (socket == null)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
socket.BeginConnect(IP, port, new AsyncCallback(sendCallback), null);
}
private void connectCallback(IAsyncResult ar)
{
//try
//{
socket.EndConnect(ar);
if (OnConnect != null)
{
OnConnect(this, Connected);
}
//}
//catch
//{
//}
}
public void Send(byte[] data, int index, int length)
{
socket.BeginSend(BitConverter.GetBytes(length), 0, 4, SocketFlags.None, new AsyncCallback(sendCallback), null);
socket.BeginSend(data, index, length, SocketFlags.None, new AsyncCallback(sendCallback), null);
}
private void sendCallback(IAsyncResult ar)
{
try
{
int sent = socket.EndSend(ar); ( errrors here )
if (OnSend != null)
{
OnSend(this, sent);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
return;
}
}
public void Disconnect()
{
try
{
if (socket.Connected)
{
socket.Close();
socket = null;
if (OnDisconnect != null)
{
OnDisconnect(this);
}
}
}
catch
{
}
}
you should not have two pending BeginSend operations.
Send the size and then the buffer when it completes:
public void Send(byte[] data, int index, int length)
{
//add data as state
socket.BeginSend(BitConverter.GetBytes(length), 0, 4, SocketFlags.None, sendCallback, data);
}
private void sendCallback(IAsyncResult ar)
{
try
{
int sent = socket.EndSend(ar); ( errrors here )
// check if data was attached.
if (ar.AsyncState != null)
{
byte[] buffer = (byte[])ar.AsyncState;
socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, sendCallback, null);
return;
}
if (OnSend != null)
{
OnSend(this, sent);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
return;
}
}
You can also use the BeginSend overload which takes a list of buffers.

Categories