Add P2PDatagramSocket and P2PStreamSocket interfaces.
[chromium-blink-merge.git] / remoting / base / buffered_socket_writer.h
blob255b2e5d0f26911f267df2df51975c50b301b88b
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.
5 #ifndef REMOTING_BASE_BUFFERED_SOCKET_WRITER_H_
6 #define REMOTING_BASE_BUFFERED_SOCKET_WRITER_H_
8 #include <list>
10 #include "base/callback.h"
11 #include "base/memory/weak_ptr.h"
12 #include "base/synchronization/lock.h"
13 #include "base/threading/thread_checker.h"
14 #include "net/base/completion_callback.h"
15 #include "net/base/io_buffer.h"
17 namespace net {
18 class Socket;
19 } // namespace net
21 namespace remoting {
23 // BufferedSocketWriter implement write data queue for stream sockets.
24 class BufferedSocketWriter {
25 public:
26 typedef base::Callback<int(const scoped_refptr<net::IOBuffer>& buf,
27 int buf_len,
28 const net::CompletionCallback& callback)>
29 WriteCallback;
30 typedef base::Callback<void(int)> WriteFailedCallback;
32 static scoped_ptr<BufferedSocketWriter> CreateForSocket(
33 net::Socket* socket,
34 const WriteFailedCallback& write_failed_callback);
36 BufferedSocketWriter();
37 virtual ~BufferedSocketWriter();
39 // Initializes the writer. |write_callback| is called to write data to the
40 // socket. |write_failed_callback| is called when write operation fails.
41 // Writing stops after the first failed write.
42 void Init(const WriteCallback& write_callback,
43 const WriteFailedCallback& write_failed_callback);
45 // Puts a new data chunk in the buffer. Returns false if writing has stopped
46 // because of an error.
47 bool Write(const scoped_refptr<net::IOBufferWithSize>& buffer,
48 const base::Closure& done_task);
50 // Returns true when there is data waiting to be written.
51 bool has_data_pending() { return !queue_.empty(); }
53 private:
54 struct PendingPacket;
55 typedef std::list<PendingPacket*> DataQueue;
57 // Returns true if the writer is closed due to an error.
58 bool is_closed();
60 void DoWrite();
61 void HandleWriteResult(int result);
62 void OnWritten(int result);
64 base::ThreadChecker thread_checker_;
66 WriteCallback write_callback_;
67 WriteFailedCallback write_failed_callback_;
69 DataQueue queue_;
71 bool write_pending_ = false;
73 base::WeakPtrFactory<BufferedSocketWriter> weak_factory_;
76 } // namespace remoting
78 #endif // REMOTING_BASE_BUFFERED_SOCKET_WRITER_H_