欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實現(xiàn)TCP互發(fā)消息

 更新時間:2020年07月28日 15:18:46   作者:~故事的小黃花~  
這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)TCP互發(fā)消息,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了Java實現(xiàn)TCP互發(fā)消息的具體代碼,供大家參考,具體內(nèi)容如下

TCP客戶端:

package tcp;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClient {
  public static void main(String[] args) {
    Socket socket =null;
    OutputStream os =null;
    try {
      //創(chuàng)建socket對象,指明服務(wù)器端的ip和端口號
      InetAddress inet = InetAddress.getByName("127.0.0.1");
      socket = new Socket(inet, 8888);
      //獲取一個輸出流,用于輸出數(shù)據(jù)
      os = socket.getOutputStream();
      //寫出數(shù)據(jù)的操作
      os.write("你好,我是客戶端".getBytes());
    }catch(IOException e){
      e.printStackTrace();
    }finally {
      //資源的關(guān)閉
      if(os!=null){
        try{
          os.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
      if(socket!=null){
        try {
          socket.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
    }
  }
}

TCP服務(wù)端:

package tcp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

class TcpServer{
  public static void main(String[] args) {
    ServerSocket ss=null;
    Socket socket=null;
    InputStream is=null;
    ByteArrayOutputStream baos =null;
    try {
      //創(chuàng)建服務(wù)器端的ServerSocket,指明自己的端口
      ss = new ServerSocket(8888);
      //調(diào)用accept()表示接收來自于客戶端的socket
      socket = ss.accept();
      //獲取輸入流中的數(shù)據(jù)
      is = socket.getInputStream();
      /*讀取輸入流中的數(shù)據(jù)(ByteArrayOutputStream可以把字節(jié)一次性記錄下來,
      這樣就可以避免一些字符的字節(jié)碼不一致導(dǎo)致發(fā)送后解析出現(xiàn)亂碼;
      ByteArrayOutputStream的功能與StringBuilder的作用有異曲同工之妙。)
      */
      baos = new ByteArrayOutputStream();
      byte[] buffer = new byte[5];
      int len;
      while ((len = is.read(buffer)) != -1) {
        baos.write(buffer, 0, len);
      }
      System.out.println(baos.toString());
    }catch (IOException e){
      e.printStackTrace();
    }
    finally{
      //關(guān)閉流
      if (baos!=null){
        try {
          baos.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
      if (is!=null){
        try {
          is.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
      if (socket!=null){
        try {
          socket.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
      if (ss!=null){
        try {
          ss.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
    }
  }
}

注意:在Intellij idea中運行時,需先打開兩個端的平行運行設(shè)置,操作如下:

最后的運行結(jié)果如下:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論