This is a small routine( i have written line numbers so it will be easier to make reference) I have for transferring data from my desktop application to my mobile device. It is working perfectly but I am unable to handle the exceptions properly. if i write my code as it is below the System.Net.Sockets.SocketException
exception is handled but since client fails to connect thats why the next line(17) produces an exception
System.InvalidOperationException: 'The operation is not allowed on non-connected sockets.
Now if i try to put line 17 and 18 in try then another error arises that stream becomes a local object and due to which line 24 produces error.
If i declare stream in the beginning then another error occurs on line 24
ERROR :use of unassigned variable stream.
its sort of a deadlock for me i am unable to work my way through it. Thanks in Advance!!
C#
1 void BluetoothClientConnectCallback(IAsyncResult result)
2 {
3 BluetoothClient client = (BluetoothClient)result.AsyncState;
4 Stream stream;
5
6 try
7 {
8 client.EndConnect(result);
9 }
10
11 catch (System.Net.Sockets.SocketException)
12 {
13 MessageBox.Show("Unable to connect to device!", "Error",
MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
14
15 }
16
17 stream = client.GetStream();
18 stream.ReadTimeout = 1000;
19 while (true)
20 {
21 while (!ready) ;
23 message = Encoding.ASCII.GetBytes("{");
24 stream.Write(message, 0, 1);
25 ready = false;
26
27 }