1. 程式人生 > >TCP/IP Socket傳送接收圖片demo

TCP/IP Socket傳送接收圖片demo

一個例項通過client端和server端通訊

客戶端通過TCP/IP傳輸資原始檔,比如圖片,文字,音訊,視訊等.....

服務端接受到檔案存入本地磁碟,返回接受到:“收到來自於"+s.getInetAddress().getHostName()+"的資訊”

package com.ykw.net;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import org.junit.Test; //TCP程式設計例三:從客戶端傳送檔案給服務端,服務端儲存到本地。並返回"傳送成功"給客戶端。並關閉相應的連線 public class TestTCP3 { @Test public void client()throws Exception{ //1.建立Socket的物件 Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9898);
//2.從本地獲取一個檔案傳送給服務端 OutputStream os = socket.getOutputStream(); FileInputStream fis = new FileInputStream(new File("1.jpg")); byte[] b = new byte[1024]; int len; while((len=fis.read(b))!=-1){ os.write(b,0,len); } socket.shutdownOutput();
//3.接受來自於服務端的資訊 InputStream is = socket.getInputStream(); byte[] b1 = new byte[1024]; int len1; while((len1 = is.read(b1))!=-1){ String str = new String(b1,0,len1); System.out.println(str); } //4.關閉相應的流和Socket物件 is.close(); os.close(); fis.close(); socket.close(); } @Test public void server()throws Exception{ //1.建立一個ServerSocket物件 ServerSocket ss = new ServerSocket(9898); //2.呼叫其accept()方法,返回一個Socket物件 Socket s = ss.accept(); //3.將從客戶端傳送過來的資訊儲存到本地 InputStream is = s.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("D://5.jpg")); byte[] b = new byte[1024]; int len; while((len = is.read(b))!=-1){ fos.write(b,0,len); } System.out.println("收到來自於"+s.getInetAddress().getHostAddress()+"的檔案"); //4.傳送“接收成功”的資訊反饋給客戶端 OutputStream os = s.getOutputStream(); os.write("您傳送的圖片我已接收成功".getBytes()); //5.關閉相應的流和Socket及ServerSocket的物件 os.close(); fos.close(); is.close(); s.close(); ss.close(); } }