一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - Java Socket編程實例(四)- NIO TCP實踐

Java Socket編程實例(四)- NIO TCP實踐

2020-05-17 12:19kingxss JAVA教程

這篇文章主要講解Java Socket編程中NIO TCP的實例,希望能給大家做一個參考。

一、回傳協議接口和TCP方式實現:

1.接口:

?
1
2
3
4
5
6
7
8
import java.nio.channels.SelectionKey;
import java.io.IOException;
 
public interface EchoProtocol {
 void handleAccept(SelectionKey key) throws IOException;
 void handleRead(SelectionKey key) throws IOException;
 void handleWrite(SelectionKey key) throws IOException;
}

2.實現:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.nio.channels.*;
import java.nio.ByteBuffer;
import java.io.IOException;
 
public class TCPEchoSelectorProtocol implements EchoProtocol{
  private int bufSize; // Size of I/O buffer
 
  public EchoSelectorProtocol(int bufSize) {
    this.bufSize = bufSize;
  }
 
  public void handleAccept(SelectionKey key) throws IOException {
    SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();
    clntChan.configureBlocking(false); // Must be nonblocking to register
    // Register the selector with new channel for read and attach byte buffer
    clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufSize));
     
  }
 
  public void handleRead(SelectionKey key) throws IOException {
    // Client socket channel has pending data
    SocketChannel clntChan = (SocketChannel) key.channel();
    ByteBuffer buf = (ByteBuffer) key.attachment();
    long bytesRead = clntChan.read(buf);
    if (bytesRead == -1) { // Did the other end close?
      clntChan.close();
    } else if (bytesRead > 0) {
      // Indicate via key that reading/writing are both of interest now.
      key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    }
  }
 
  public void handleWrite(SelectionKey key) throws IOException {
    /*
     * Channel is available for writing, and key is valid (i.e., client channel
     * not closed).
     */
    // Retrieve data read earlier
    ByteBuffer buf = (ByteBuffer) key.attachment();
    buf.flip(); // Prepare buffer for writing
    SocketChannel clntChan = (SocketChannel) key.channel();
    clntChan.write(buf);
    if (!buf.hasRemaining()) { // Buffer completely written? 
      //Nothing left, so no longer interested in writes
      key.interestOps(SelectionKey.OP_READ);
    }
    buf.compact(); // Make room for more data to be read in
  }
 
}

二、NIO TCP客戶端:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
 
public class TCPEchoClientNonblocking {
 
  public static void main(String args[]) throws Exception {
    String server = "127.0.0.1"; // Server name or IP address
    // Convert input String to bytes using the default charset
    byte[] argument = "0123456789abcdefghijklmnopqrstuvwxyz".getBytes();
 
    int servPort = 5500;
 
    // Create channel and set to nonblocking
    SocketChannel clntChan = SocketChannel.open();
    clntChan.configureBlocking(false);
 
    // Initiate connection to server and repeatedly poll until complete
    if (!clntChan.connect(new InetSocketAddress(server, servPort))) {
      while (!clntChan.finishConnect()) {
        System.out.print("."); // Do something else
      }
    }
    ByteBuffer writeBuf = ByteBuffer.wrap(argument);
    ByteBuffer readBuf = ByteBuffer.allocate(argument.length);
    int totalBytesRcvd = 0; // Total bytes received so far
    int bytesRcvd; // Bytes received in last read
    while (totalBytesRcvd < argument.length) {
      if (writeBuf.hasRemaining()) {
        clntChan.write(writeBuf);
      }
      if ((bytesRcvd = clntChan.read(readBuf)) == -1) {
        throw new SocketException("Connection closed prematurely");
      }
      totalBytesRcvd += bytesRcvd;
      System.out.print("."); // Do something else
    }
 
    System.out.println("Received: " + // convert to String per default charset
        new String(readBuf.array(), 0, totalBytesRcvd).length());
    clntChan.close();
  }
}

三、NIO TCP服務端:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;
 
public class TCPServerSelector {
  private static final int BUFSIZE = 256; // Buffer size (bytes)
  private static final int TIMEOUT = 3000; // Wait timeout (milliseconds)
   
  public static void main(String[] args) throws IOException {
    int[] ports = {5500};
    // Create a selector to multiplex listening sockets and connections
    Selector selector = Selector.open();
 
    // Create listening socket channel for each port and register selector
    for (int port : ports) {
      ServerSocketChannel listnChannel = ServerSocketChannel.open();
      listnChannel.socket().bind(new InetSocketAddress(port));
      listnChannel.configureBlocking(false); // must be nonblocking to register
      // Register selector with channel. The returned key is ignored
      listnChannel.register(selector, SelectionKey.OP_ACCEPT);
    }
 
    // Create a handler that will implement the protocol
    TCPProtocol protocol = new TCPEchoSelectorProtocol(BUFSIZE);
 
    while (true) { // Run forever, processing available I/O operations
      // Wait for some channel to be ready (or timeout)
      if (selector.select(TIMEOUT) == 0) { // returns # of ready chans
        System.out.print(".");
        continue;
      }
 
      // Get iterator on set of keys with I/O to process
      Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
      while (keyIter.hasNext()) {
        SelectionKey key = keyIter.next(); // Key is bit mask
        // Server socket channel has pending connection requests?
        if (key.isAcceptable()) {
          System.out.println("----accept-----");
          protocol.handleAccept(key);
        }
        // Client socket channel has pending data?
        if (key.isReadable()) {
          System.out.println("----read-----");
          protocol.handleRead(key);
        }
        // Client socket channel is available for writing and 
        // key is valid (i.e., channel not closed)?
        if (key.isValid() && key.isWritable()) {
          System.out.println("----write-----");
          protocol.handleWrite(key);
        }
        keyIter.remove(); // remove from set of selected keys
      }
    }
  }
   
}

以上就是本文的全部內容,查看更多Java的語法,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲AV久久无码精品蜜桃 | 欧美在线视频一区在线观看 | 99精品国产综合久久久久 | 国产私拍精品88福利视频 | 扒开女人屁股眼看个够 | 国产乱码在线精品可播放 | 国产小视频在线免费 | 好深快点再快点好爽视频 | 草草在线免费视频 | 韩国一大片a毛片女同 | 国产精品久久久久久久人人看 | 国产一区二区播放 | 亚洲成a人片777777久久 | 公翁的舌尖研磨她的花蒂小说 | 国产日韩欧美综合在线 | 亚洲视频免 | 亚洲国产免费 | katsuniav在线播放 | girlfriend动漫在线播放 | 日韩一区视频在线 | 国产欧美日韩免费一区二区 | 免费在线观看日韩 | 国产精品一区二区三区久久 | 无人区大片免费播放器 | 深夜影院深a | 久久精麻豆亚洲AV国产品 | 国产爱啪啪 | 国产小视频在线免费 | 久久青青草视频在线观 | 免费又爽又黄禁片视频在线播放 | 天天av天天翘天天综合网 | 国产亚洲福利一区二区免费看 | 亚洲H成年动漫在线观看不卡 | 99在线精品视频 | 成年人在线免费观看视频网站 | 日韩成人一级 | 日韩免费高清完整版 | 四虎2023| 第一次破学生处破 | 亚洲另类激情 | 爱情岛论坛亚洲一号路线 |