1. 程式人生 > 程式設計 >Java實現TCP互發訊息

Java實現TCP互發訊息

本文例項為大家分享了Java實現TCP互發訊息的具體程式碼,供大家參考,具體內容如下

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 {
      //建立socket物件,指明伺服器端的ip和埠號
      InetAddress inet = InetAddress.getByName("127.0.0.1");
      socket = new Socket(inet,8888);
      //獲取一個輸出流,用於輸出資料
      os = socket.getOutputStream();
      //寫出資料的操作
      os.write("你好,我是客戶端".getBytes());
    }catch(IOException e){
      e.printStackTrace();
    }finally {
      //資源的關閉
      if(os!=null){
        try{
          os.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
      if(socket!=null){
        try {
          socket.close();
        }catch (IOException e){
          e.printStackTrace();
        }
      }
    }
  }
}

TCP服務端:

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 {
      //建立伺服器端的ServerSocket,指明自己的埠
      ss = new ServerSocket(8888);
      //呼叫accept()表示接收來自於客戶端的socket
      socket = ss.accept();
      //獲取輸入流中的資料
      is = socket.getInputStream();
      /*讀取輸入流中的資料(ByteArrayOutputStream可以把位元組一次性記錄下來,
      這樣就可以避免一些字元的位元組碼不一致導致傳送後解析出現亂碼;
      ByteArrayOutputStream的功能與StringBuilder的作用有異曲同工之妙。)
      */
      baos = new ByteArrayOutputStream();
      byte[] buffer = new byte[5];
      int len;
      while ((len = is.read(buffer)) != -1) {
        baos.write(buffer,len);
      }
      System.out.println(baos.toString());
    }catch (IOException e){
      e.printStackTrace();
    }
    finally{
      //關閉流
      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中執行時,需先開啟兩個端的平行執行設定,操作如下:

Java實現TCP互發訊息

Java實現TCP互發訊息

最後的執行結果如下:

Java實現TCP互發訊息

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。