Socket
·功能:TCP客戶端套接字
·構造方法:
Socket(InetAddress address, int port)
創建一個流套接字並將其連接到指定 IP 地址的指定端口號
·常用方法:
1.getInetAddress
獲得InetAddress的相關信息
2.getInputStream
獲得此TCP連接的輸入流
3.getOutPutStream
獲得此TCP連接的輸出流
ServerSocket
·功能: TCP服務端套接字
·構造方法:
ServerSocket(int port)
創建綁定到特定端口的服務器套接字。
·常用方法:
1.accept
獲得TCP連接的客戶端的socket
2.isClosed
獲得ServerSocket的關閉狀態
TCP服務器端
TcpServer.java
服務器端采用多線程的方式,每建立一個連接就啟動一個java線程,發送圖片給客戶端,之后關閉此TCP連接
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TcpServer extends Thread{ Socket clientSocket; public TcpServer(Socket clientSocket) { super(); this.clientSocket = clientSocket; } @Override public void run() { try { //獲得客戶端的ip地址和主機名 String clientAddress = clientSocket.getInetAddress().getHostAddress(); String clientHostName = clientSocket.getInetAddress().getHostName(); System.out.println(clientHostName + "(" + clientAddress + ")" + " 連接成功!"); System.out.println("Now, 傳輸圖片數據..........."); long startTime = System.currentTimeMillis(); //獲取客戶端的OutputStream OutputStream out = clientSocket.getOutputStream(); //傳出圖片數據 FileInputStream in = new FileInputStream(new File("/home/gavinzhou/test.jpg")); byte[] data = new byte[4096]; int length = 0; while((length = in.read(data)) != -1){ out.write(data, 0, length); //寫出數據 } long endTime = System.currentTimeMillis(); //提示信息 System.out.println(clientHostName + "(" + clientAddress + ")" + " 圖片傳輸成功," + "用時:" + ((endTime-startTime)) + "ms"); //關閉資源 in.close(); clientSocket.close(); System.out.println("連接關閉!"); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { //建立TCP連接服務,綁定端口 ServerSocket tcpServer = new ServerSocket(9090); //接受連接,傳圖片給連接的客戶端,每個TCP連接都是一個java線程 while(true){ Socket clientSocket = tcpServer.accept(); new TcpServer(clientSocket).start(); } } }
TCP客戶端
TcpClient
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.Socket; public class TcpClient { public static void main(String[] args) throws IOException { // 建立TCP服務 // 連接本機的TCP服務器 Socket socket = new Socket(InetAddress.getLocalHost(), 9090); // 獲得輸入流 InputStream inputStream = socket.getInputStream(); // 寫入數據 FileOutputStream out = new FileOutputStream(new File("../save.jpg")); byte[] data = new byte[4096]; int length = 0; while((length = inputStream.read(data)) != -1){ out.write(data, 0, length); } //關閉資源 out.close(); socket.close(); } }
結果
首先,命令行啟動服務器端,之后啟動客戶端,結果如下:
圖片比較小,速度很快!