View Javadoc
1   /*
2    * Copyright 2021 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel.kqueue;
17  
18  import io.netty.channel.Channel;
19  import io.netty.channel.ChannelMetadata;
20  import io.netty.channel.ChannelOutboundBuffer;
21  
22  import java.io.IOException;
23  
24  abstract class AbstractKQueueDatagramChannel extends AbstractKQueueChannel {
25  
26      private static final ChannelMetadata METADATA = new ChannelMetadata(true, 16);
27  
28      AbstractKQueueDatagramChannel(Channel parent, BsdSocket fd, boolean active) {
29          super(parent, fd, active);
30      }
31  
32      @Override
33      public ChannelMetadata metadata() {
34          return METADATA;
35      }
36  
37      protected abstract boolean doWriteMessage(Object msg) throws Exception;
38  
39      @Override
40      protected void doWrite(ChannelOutboundBuffer in) throws Exception {
41          int maxMessagesPerWrite = maxMessagesPerWrite();
42          while (maxMessagesPerWrite > 0) {
43              Object msg = in.current();
44              if (msg == null) {
45                  break;
46              }
47  
48              try {
49                  boolean done = false;
50                  for (int i = config().getWriteSpinCount(); i > 0; --i) {
51                      if (doWriteMessage(msg)) {
52                          done = true;
53                          break;
54                      }
55                  }
56  
57                  if (done) {
58                      in.remove();
59                      maxMessagesPerWrite--;
60                  } else {
61                      break;
62                  }
63              } catch (IOException e) {
64                  maxMessagesPerWrite--;
65  
66                  // Continue on write error as a DatagramChannel can write to multiple remote peers
67                  //
68                  // See https://github.com/netty/netty/issues/2665
69                  in.remove(e);
70              }
71          }
72  
73          // Whether all messages were written or not.
74          writeFilter(!in.isEmpty());
75      }
76  }