buffered_socket_writer.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef REMOTING_BASE_BUFFERED_SOCKET_WRITER_H_
  5. #define REMOTING_BASE_BUFFERED_SOCKET_WRITER_H_
  6. #include <list>
  7. #include <memory>
  8. #include "base/callback.h"
  9. #include "base/memory/weak_ptr.h"
  10. #include "base/synchronization/lock.h"
  11. #include "base/threading/thread_checker.h"
  12. #include "net/base/completion_once_callback.h"
  13. #include "net/base/io_buffer.h"
  14. #include "net/traffic_annotation/network_traffic_annotation.h"
  15. namespace net {
  16. class Socket;
  17. } // namespace net
  18. namespace remoting {
  19. // BufferedSocketWriter implement write data queue for stream sockets.
  20. class BufferedSocketWriter {
  21. public:
  22. typedef base::RepeatingCallback<int(
  23. const scoped_refptr<net::IOBuffer>& buf,
  24. int buf_len,
  25. net::CompletionOnceCallback callback,
  26. const net::NetworkTrafficAnnotationTag& traffic_annotation)>
  27. WriteCallback;
  28. typedef base::OnceCallback<void(int)> WriteFailedCallback;
  29. static std::unique_ptr<BufferedSocketWriter> CreateForSocket(
  30. net::Socket* socket,
  31. WriteFailedCallback write_failed_callback);
  32. BufferedSocketWriter();
  33. virtual ~BufferedSocketWriter();
  34. // Starts the writer. |write_callback| is called to write data to the
  35. // socket. |write_failed_callback| is called when write operation fails.
  36. // Writing stops after the first failed write.
  37. void Start(const WriteCallback& write_callback,
  38. WriteFailedCallback write_failed_callback);
  39. // Puts a new data chunk in the buffer. If called before Start() then all data
  40. // is buffered until Start().
  41. void Write(scoped_refptr<net::IOBufferWithSize> buffer,
  42. base::OnceClosure done_task,
  43. const net::NetworkTrafficAnnotationTag& traffic_annotation);
  44. // Returns true when there is data waiting to be written.
  45. bool has_data_pending() { return !queue_.empty(); }
  46. private:
  47. struct PendingPacket;
  48. void DoWrite();
  49. void HandleWriteResult(int result);
  50. void OnWritten(int result);
  51. base::ThreadChecker thread_checker_;
  52. WriteCallback write_callback_;
  53. WriteFailedCallback write_failed_callback_;
  54. bool closed_ = false;
  55. std::list<std::unique_ptr<PendingPacket>> queue_;
  56. bool write_pending_ = false;
  57. base::WeakPtrFactory<BufferedSocketWriter> weak_factory_{this};
  58. };
  59. } // namespace remoting
  60. #endif // REMOTING_BASE_BUFFERED_SOCKET_WRITER_H_