最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java 基礎(chǔ)知識(shí)之網(wǎng)絡(luò)通信(TCP通信、UDP通信、多播以及NIO)總結(jié)

 更新時(shí)間:2017年03月06日 14:52:40   投稿:lqh  
這篇文章主要介紹了java 基礎(chǔ)知識(shí)之網(wǎng)絡(luò)通信總結(jié)的相關(guān)資料,包括TCP通信、UDP通信、多播以及NIO,需要的朋友可以參考下

java 基礎(chǔ)知識(shí)之網(wǎng)路通信總結(jié)

在這篇文章里,我們主要討論如何使用Java實(shí)現(xiàn)網(wǎng)絡(luò)通信,包括TCP通信、UDP通信、多播以及NIO。

  TCP連接

  TCP的基礎(chǔ)是Socket,在TCP連接中,我們會(huì)使用ServerSocket和Socket,當(dāng)客戶端和服務(wù)器建立連接以后,剩下的基本就是對(duì)I/O的控制了。

  我們先來(lái)看一個(gè)簡(jiǎn)單的TCP通信,它分為客戶端和服務(wù)器端。

  客戶端代碼如下:

簡(jiǎn)單的TCP客戶端
import java.net.*;
import java.io.*;
public class SimpleTcpClient {

  public static void main(String[] args) throws IOException
  {
    Socket socket = null;
    BufferedReader br = null;
    PrintWriter pw = null;
    BufferedReader brTemp = null;
    try
    {
      socket = new Socket(InetAddress.getLocalHost(), 5678);
      br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      pw = new PrintWriter(socket.getOutputStream());
      brTemp = new BufferedReader(new InputStreamReader(System.in));
      while(true)
      {
        String line = brTemp.readLine();
        pw.println(line);
        pw.flush();
        if (line.equals("end")) break;
        System.out.println(br.readLine());
      }
    }
    catch(Exception ex)
    {
      System.err.println(ex.getMessage());
    }
    finally
    {
      if (socket != null) socket.close();
      if (br != null) br.close();
      if (brTemp != null) brTemp.close();
      if (pw != null) pw.close();
    }
  }
}

  服務(wù)器端代碼如下:

簡(jiǎn)單版本TCP服務(wù)器端
import java.net.*;
import java.io.*;
public class SimpleTcpServer {

  public static void main(String[] args) throws IOException
  {
    ServerSocket server = null;
    Socket client = null;
    BufferedReader br = null;
    PrintWriter pw = null;
    try
    {
      server = new ServerSocket(5678);
      client = server.accept();
      br = new BufferedReader(new InputStreamReader(client.getInputStream()));
      pw = new PrintWriter(client.getOutputStream());
      while(true)
      {
        String line = br.readLine();
        pw.println("Response:" + line);
        pw.flush();
        if (line.equals("end")) break;
      }
    }
    catch(Exception ex)
    {
      System.err.println(ex.getMessage());
    }
    finally
    {
      if (server != null) server.close();
      if (client != null) client.close();
      if (br != null) br.close();
      if (pw != null) pw.close();
    }
  }
}

  這里的服務(wù)器的功能非常簡(jiǎn)單,它接收客戶端發(fā)來(lái)的消息,然后將消息“原封不動(dòng)”的返回給客戶端。當(dāng)客戶端發(fā)送“end”時(shí),通信結(jié)束。

  上面的代碼基本上勾勒了TCP通信過(guò)程中,客戶端和服務(wù)器端的主要框架,我們可以發(fā)現(xiàn),上述的代碼中,服務(wù)器端在任何時(shí)刻,都只能處理來(lái)自客戶端的一個(gè)請(qǐng)求,它是串行處理的,不能并行,這和我們印象里的服務(wù)器處理方式不太相同,我們可以為服務(wù)器添加多線程,當(dāng)一個(gè)客戶端的請(qǐng)求進(jìn)入后,我們就創(chuàng)建一個(gè)線程,來(lái)處理對(duì)應(yīng)的請(qǐng)求。

  改善后的服務(wù)器端代碼如下:

多線程版本的TCP服務(wù)器端
import java.net.*;
import java.io.*;
public class SmartTcpServer {
  public static void main(String[] args) throws IOException
  {
    ServerSocket server = new ServerSocket(5678);
    while(true)
    {
      Socket client = server.accept();
      Thread thread = new ServerThread(client);
      thread.start();
    }
  }
}

class ServerThread extends Thread
{
  private Socket socket = null;

  public ServerThread(Socket socket)
  {
    this.socket = socket;
  }
  
  public void run() {
    BufferedReader br = null;
    PrintWriter pw = null;
    try
    {
      br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      pw = new PrintWriter(socket.getOutputStream());
      while(true)
      {
        String line = br.readLine();
        pw.println("Response:" + line);
        pw.flush();
        if (line.equals("end")) break;
      }
    }
    catch(Exception ex)
    {
      System.err.println(ex.getMessage());
    }
    finally
    {
      if (socket != null)
        try {
          socket.close();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      if (br != null)
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      if (pw != null) pw.close();
    }
  }
}

  修改后的服務(wù)器端,就可以同時(shí)處理來(lái)自客戶端的多個(gè)請(qǐng)求了。

  在編程的過(guò)程中,我們會(huì)有“資源”的概念,例如數(shù)據(jù)庫(kù)連接就是一個(gè)典型的資源,為了提升性能,我們通常不會(huì)直接銷毀數(shù)據(jù)庫(kù)連接,而是使用數(shù)據(jù)庫(kù)連接池的方式來(lái)對(duì)多個(gè)數(shù)據(jù)庫(kù)連接進(jìn)行管理,已實(shí)現(xiàn)重用的目的。對(duì)于Socket連接來(lái)說(shuō),它也是一種資源,當(dāng)我們的程序需要大量的Socket連接時(shí),如果每個(gè)連接都需要重新建立,那么將會(huì)是一件非常沒有效率的做法。

  和數(shù)據(jù)庫(kù)連接池類似,我們也可以設(shè)計(jì)TCP連接池,這里的思路是我們用一個(gè)數(shù)組來(lái)維持多個(gè)Socket連接,另外一個(gè)狀態(tài)數(shù)組來(lái)描述每個(gè)Socket連接是否正在使用,當(dāng)程序需要Socket連接時(shí),我們遍歷狀態(tài)數(shù)組,取出第一個(gè)沒被使用的Socket連接,如果所有連接都在使用,拋出異常。這是一種很直觀簡(jiǎn)單的“調(diào)度策略”,在很多開源或者商業(yè)的框架中(Apache/Tomcat),都會(huì)有類似的“資源池”。

  TCP連接池的代碼如下:

一個(gè)簡(jiǎn)單的TCP連接池
import java.net.*;
import java.io.*;
public class TcpConnectionPool {

  private InetAddress address = null;
  private int port;
  private Socket[] arrSockets = null;
  private boolean[] arrStatus = null;
  private int count;
  
  public TcpConnectionPool(InetAddress address, int port, int count)
  {
    this.address = address;
    this.port = port;
    this .count = count;
    arrSockets = new Socket[count];
    arrStatus = new boolean[count];
    
    init();
  }
  
  private void init()
  {
    try
    {
      for (int i = 0; i < count; i++)
      {
        arrSockets[i] = new Socket(address.getHostAddress(), port);
        arrStatus[i] = false;
      }
    }
    catch(Exception ex)
    {
      System.err.println(ex.getMessage());
    }
  }
  
  public Socket getConnection()
  {
    if (arrSockets == null) init();
    int i = 0;
    for(i = 0; i < count; i++)
    {
      if (arrStatus[i] == false) 
      {
        arrStatus[i] = true;
        break;
      }
    }
    if (i == count) throw new RuntimeException("have no connection availiable for now.");
    
    return arrSockets[i];
  }
  
  public void releaseConnection(Socket socket)
  {
    if (arrSockets == null) init();
    for (int i = 0; i < count; i++)
    {
      if (arrSockets[i] == socket)
      {
        arrStatus[i] = false;
        break;
      }
    }
  }
  
  public void reBuild()
  {
    init();
  }
  
  public void destory()
  {
    if (arrSockets == null) return;
    
    for(int i = 0; i < count; i++)
    {
      try
      {
        arrSockets[i].close();
      }
      catch(Exception ex)
      {
        System.err.println(ex.getMessage());
        continue;
      }
    }
  }
}

  UDP連接

  UDP是一種和TCP不同的連接方式,它通常應(yīng)用在對(duì)實(shí)時(shí)性要求很高,對(duì)準(zhǔn)確定要求不高的場(chǎng)合,例如在線視頻。UDP會(huì)有“丟包”的情況發(fā)生,在TCP中,如果Server沒有啟動(dòng),Client發(fā)消息時(shí),會(huì)報(bào)出異常,但對(duì)UDP來(lái)說(shuō),不會(huì)產(chǎn)生任何異常。

  UDP通信使用的兩個(gè)類時(shí)DatagramSocket和DatagramPacket,后者存放了通信的內(nèi)容。

  下面是一個(gè)簡(jiǎn)單的UDP通信例子,同TCP一樣,也分為Client和Server兩部分,Client端代碼如下:

UDP通信客戶端
import java.net.*;
import java.io.*;
public class UdpClient {

  public static void main(String[] args)
  {
    try
    {
      InetAddress host = InetAddress.getLocalHost();
      int port = 5678;
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      while(true)
      {
        String line = br.readLine();
        byte[] message = line.getBytes();
        DatagramPacket packet = new DatagramPacket(message, message.length, host, port);
        DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();
        if (line.equals("end")) break;
      }
      br.close();
    }
    catch(Exception ex)
    {
      System.err.println(ex.getMessage());
    }
  }
}

  Server端代碼如下:

UDP通信服務(wù)器端
import java.net.*;
import java.io.*;
public class UdpServer {

  public static void main(String[] args)
  {
    try
    {
      int port = 5678;
      DatagramSocket dsSocket = new DatagramSocket(port);
      byte[] buffer = new byte[1024];
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      while(true)
      {
        dsSocket.receive(packet);
        String message = new String(buffer, 0, packet.getLength());
        System.out.println(packet.getAddress().getHostName() + ":" + message);
        if (message.equals("end")) break;
        packet.setLength(buffer.length);
      }
      dsSocket.close();
    }
    catch(Exception ex)
    {
      System.err.println(ex.getMessage());
    }
  }
}

  這里,我們也假設(shè)和TCP一樣,當(dāng)Client發(fā)出“end”消息時(shí),認(rèn)為通信結(jié)束,但其實(shí)這樣的設(shè)計(jì)不是必要的,Client端可以隨時(shí)斷開,并不需要關(guān)心Server端狀態(tài)。

  多播(Multicast)

  多播采用和UDP類似的方式,它會(huì)使用D類IP地址和標(biāo)準(zhǔn)的UDP端口號(hào),D類IP地址是指224.0.0.0到239.255.255.255之間的地址,不包括224.0.0.0。

  多播會(huì)使用到的類是MulticastSocket,它有兩個(gè)方法需要關(guān)注:joinGroup和leaveGroup。

  下面是一個(gè)多播的例子,Client端代碼如下:

多播通信客戶端
import java.net.*;
import java.io.*;
public class MulticastClient {

  public static void main(String[] args)
  {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try
    {
      InetAddress address = InetAddress.getByName("230.0.0.1");
      int port = 5678;
      while(true)
      {
        String line = br.readLine();
        byte[] message = line.getBytes();
        DatagramPacket packet = new DatagramPacket(message, message.length, address, port);
        MulticastSocket multicastSocket = new MulticastSocket();
        multicastSocket.send(packet);
        if (line.equals("end")) break;
      }
      br.close();
    }
    catch(Exception ex)
    {
      System.err.println(ex.getMessage());
    }
  }
}

  服務(wù)器端代碼如下:

多播通信服務(wù)器端
import java.net.*;
import java.io.*;
public class MulticastServer {

  public static void main(String[] args)
  {
    int port = 5678;
    try
    {
      MulticastSocket multicastSocket = new MulticastSocket(port);
      InetAddress address = InetAddress.getByName("230.0.0.1");
      multicastSocket.joinGroup(address);
      byte[] buffer = new byte[1024];
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      while(true)
      {
        multicastSocket.receive(packet);
        String message = new String(buffer, packet.getLength());
        System.out.println(packet.getAddress().getHostName() + ":" + message);
        if (message.equals("end")) break;
        packet.setLength(buffer.length);
      }
      multicastSocket.close();
    }
    catch(Exception ex)
    {
      System.err.println(ex.getMessage());
    }
  }
}

  NIO(New IO)

  NIO是JDK1.4引入的一套新的IO API,它在緩沖區(qū)管理、網(wǎng)絡(luò)通信、文件存取以及字符集操作方面有了新的設(shè)計(jì)。對(duì)于網(wǎng)絡(luò)通信來(lái)說(shuō),NIO使用了緩沖區(qū)和通道的概念。

  下面是一個(gè)NIO的例子,和我們上面提到的代碼風(fēng)格有很大的不同。

NIO例子
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.net.*;
public class NewIOSample {

  public static void main(String[] args)
  {
    String host="127.0.0.1";
    int port = 5678;
    SocketChannel channel = null;
    try
    {
      InetSocketAddress address = new InetSocketAddress(host,port);
      Charset charset = Charset.forName("UTF-8");
      CharsetDecoder decoder = charset.newDecoder();
      CharsetEncoder encoder = charset.newEncoder();
      
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      CharBuffer charBuffer = CharBuffer.allocate(1024);
      
      channel = SocketChannel.open();
      channel.connect(address);
      
      String request = "GET / \r\n\r\n";
      channel.write(encoder.encode(CharBuffer.wrap(request)));
      
      while((channel.read(buffer)) != -1)
      {
        buffer.flip();
        decoder.decode(buffer, charBuffer, false);
        charBuffer.flip();
        System.out.println(charBuffer);
        buffer.clear();
        charBuffer.clear();
      }
    }
    catch(Exception ex)
    {
      System.err.println(ex.getMessage());
    }
    finally
    {
      if (channel != null)
        try {
          channel.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
    }
  }
}

  上述代碼會(huì)試圖訪問(wèn)一個(gè)本地的網(wǎng)址,然后將其內(nèi)容打印出來(lái)。

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論

临澧县| 安泽县| 晋城| 白水县| 新余市| 西昌市| 屏东市| 柳河县| 青田县| 郓城县| 安仁县| 白玉县| 汽车| 栾城县| 龙岩市| 巴东县| 慈利县| 石狮市| 柘城县| 电白县| 绥化市| 宁武县| 霍城县| 合阳县| 新野县| 克拉玛依市| 鹤山市| 丰镇市| 商南县| 增城市| 通州市| 曲阳县| 清镇市| 利辛县| 延边| 大英县| 青田县| 犍为县| 广平县| 绍兴县| 曲松县|