In simulation of a lan-messenger in c# I am using the loopback address just for starters to check the functionality of the code.However after sending a few messages, I am getting a socket exception while using the end-connect method and then a socket exception while sending the data. Is there any reason behind this exception.
private void button1_Click(object sender, EventArgs e) { HideCaret(this.textBox1.Handle); StringBuilder sb = new StringBuilder(this.textBox1.Text); str = this.textBox2.Text; Socket newsock = new Socket(AddressFamily.InterNetwork,socketType.Stream, ProtocolType.Tcp); IPEndPoint ip = new IPEndPoint(localaddress, 5555); newsock.BeginConnect(ip, new AsyncCallback(connected), newsock); if (str != '') { sb.AppendLine(this.textBox2.Text); this.textBox1.Text = sb.ToString(); this.textBox2.Text = '\0'; send = Encoding.ASCII.GetBytes(str); try { newsock.BeginSend(send, 0, send.Length, SocketFlags.None, new AsyncCallback(sent), newsock); } catch (ArgumentException) { MessageBox.Show('arguments incorrect in begin-send call', 'Error', MessageBoxButtons.OK); } catch (SocketException) { MessageBox.Show('error in accessing socket while sending', 'Error', MessageBoxButtons.OK); } catch (ObjectDisposedException) { MessageBox.Show('socket closed while sending', 'Error', MessageBoxButtons.OK); } catch (Exception) { MessageBox.Show('error while sending', 'Error', MessageBoxButtons.OK); } } }
Please help
It’s possibly because you’re not waiting for the socket to be connected before sending data. You have two options:
connectedcallback method.You accomplish #1 by combining the data to send and the socket into a new class, then passing that as
statein your call toBeginConnect. Then move your send code to the callback method.You accomplish #2 by setting up a
System.Threading.ManualResetEventand callingWaitOneafterBeginConnect. Then callEndConnectin yourconnectedcallback method, followed by aSeton yourManualResetEvent. Then proceed to send as you have above.You’ll also probably learn more if you find out what kind of
SocketExceptionyou’re getting.From the MSDN Documentation: