     end
   end
 
+  defp enter_loop(state) do
+    case wait_for_data(state) do
+      {:noreply, new_state} ->
+        GenServerErl.enter_loop(__MODULE__, [], new_state)
+      {:stop, reason, _state} ->
+        Process.exit(self(), reason)
+    end
+  end
+
   defp wait_for_data(state) do
-    :ok = state.transport.setopts(state.socket, [{:active, :once}])
+    {_ok, closed, _error, _passive} = state.transport.messages
+    case state.transport.setopts(state.socket, [{:active, :once}]) do
+      :ok -> {:noreply, state}
+      {:error, ^closed} -> handle_socket_closed(state)
+      {:error, reason} -> handle_socket_error(state, reason)
+    end
   end
 
   def handle_info(message, state) do

    case SMPP.parse(data) do
      {:ok, nil, data} ->
        new_state = %{state | buffer: data}
        wait_for_data(state)
        {:noreply, new_state}

      {:ok, parse_result, rest_data} ->
        handle_parse_result(state, parse_result, rest_data)

          module_state: module_state,
          buffer: <<>>
        }
        enter_loop(state)

      {:stop, reason} ->
        _ = transport.close(socket)
