I wrote a simple socket application, which connects to a simple socket server application I also wrote, the server opens a socket, listens, accepts connections, sends back a string of information and then disconnects.
Problem is the client, is the harder to manage, I use blocking mode to receive, after the timeout receive is supposed to throw a socketexception (according to the docs) but it never does... please help me... the code contained in the exception handler is supposed to determine whether or not the socket is still active.... unfortunately its not working..
John
Expand|Select|Wrap|Line Numbers
- private void button1_Click(object sender, EventArgs e)
- {
- Socket hammersocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- try
- {
- hammersocket.Blocking = true;
- hammersocket.ReceiveBufferSize = 255;
- hammersocket.ReceiveTimeout = 10000;
- hammersocket.Connect("127.0.0.1", 6651);
- }
- catch (SocketException)
- {
- textBox1.Text += "\r\nConnect Failed.";
- }
- while (hammersocket.Connected)
- {
- byte[] thetext = new byte[255];
- try
- {
- int numbytes = hammersocket.Receive(thetext);
- string l = "";
- for (int x = 0; x < numbytes; x++)
- {
- l = l + (char)thetext[x];
- }
- textBox1.Text += "\r\n" + l;
- }
- catch (SocketException)
- {
- string otherstuff = "PONG";
- Encoding toascii = Encoding.ASCII;
- try
- {
- textBox1.Text += "\r\n Sending..";
- hammersocket.Send(toascii.GetBytes(otherstuff.ToCharArray()));
- textBox1.Text += "\r\n Sent...";
- }
- catch (SocketException e3)
- {
- if (e3.NativeErrorCode.Equals(10035))
- {
- textBox1.Text += "\r\nException: 10035";
- }
- else
- {
- textBox1.Text += "\r\nOther exception";
- textBox1.Text+="Connected ?:"+hammersocket.Connected.ToString();
- }
- }
- }
- this.Refresh();
- }