public bool Connect(string host, int port) { lock (initializationLock) { if (IsConnected()) { Close(); } try { socket = new TcpClient(host, port); //notify connection change if (null != connectionListener) { connectionListener.OnGazeApiConnectionStateChanged(socket.Connected); } incomingStreamHandler = new IncomingStreamHandler(socket, responseListener, connectionListener, this); incomingStreamHandler.Start(); outgoingStreamHandler = new OutgoingStreamHandler(socket, requestQueue, connectionListener, this); outgoingStreamHandler.Start(); } catch (SocketException se) { Debug.WriteLine("Unable to open socket. Is Tracker Server running? Exception: " + se.Message); //notify connection change if (null != connectionListener) { connectionListener.OnGazeApiConnectionStateChanged(false); } Close(); return(false); } catch (Exception e) { Debug.WriteLine("Exception while establishing socket connection. Is Tracker Server running? Exception: " + e.Message); Close(); return(false); } return(true); } }
private void Work() { try { string request = string.Empty; writer = new StreamWriter(socket.GetStream(), Encoding.ASCII); //while waiting for queue to populate and thread not killed while (isRunning) { try { request = blockingOutQueue.Dequeue(); writer.WriteLine(request); writer.Flush(); if (numWriteAttempt > 0) { numWriteAttempt = 0; } } catch (IOException ioe) { //Has writing to socket failed and may server be disconnected? if (numWriteAttempt++ >= NUM_WRITE_ATTEMPTS_BEFORE_FAIL) { //notify connection listener if any if (null != connectionListener) { connectionListener.OnGazeApiConnectionStateChanged(false); } //server must be disconnected, shut down network layer networkLayer.Close(); } else { //else retry request asap blockingOutQueue.Enqueue(request); } } catch (Exception e) { Debug.WriteLine("Exception while writing to socket: " + e.Message); } } } catch (Exception e) { Debug.WriteLine("Exception while establishing outgoing socket connection: " + e.Message); } finally { Debug.WriteLine("OutgoingStreamHandler closing down"); } }
private void Work() { try { reader = new StreamReader(socket.GetStream(), Encoding.ASCII); while (isRunning) { try { while (!reader.EndOfStream) { string response = reader.ReadLine(); if (null != responseListener && !string.IsNullOrEmpty(response)) { responseListener.OnGazeApiResponse(response); } } } catch (IOException ioe) { //Are we closing down or has reading from socket failed? if (isRunning && !IsSocketConnected()) { //notify connection listener if any if (null != connectionListener) { connectionListener.OnGazeApiConnectionStateChanged(false); } //server must be disconnected, shut down network layer networkLayer.Close(); } } catch (Exception e) { Debug.WriteLine("Exception while reading from socket: " + e.Message); } } } catch (Exception e) { Debug.WriteLine("Exception while establishing incoming socket connection: " + e.Message); } finally { Debug.WriteLine("IncommingStreamHandler closing down"); } }