Java利用Socket將目錄下的檔案全部傳送至Client
此文章發布於:開發者俱樂部首先會有這篇文章要感謝 9527 大大給我的指導(不知道他的名字真不好意思)
如果沒他指導我從來沒寫過Java一定要繞很大一圈
尤其沒碰過Socket利用Socket將Server端的某目錄下的檔案
設定過瀘條件後傳送至Client端站長寫完後放上來這邊給大家參考
目前不知道如果多個Client端接收的話會出什麼問題
有問題請反應給我知道喔^_^記得先設定要傳送的目錄及接收後要存放的目錄Server端:import java.io. * ;import java.net. * ;import java.util. * ;public class SocketServer {public static Vector v = new Vector();public static void main(String[] args) {int i = 1;try { //建立一個新的連線ServerSocket s = new ServerSocket(8821);for (;;) {Socket incoming = s.accept();System.out.println(ID : i
Connection Started);new SocketServer_Thread(incoming
i
v).start();i ;}} catch(Exception e) {System.out.println(Exception in line 19 : e);}}}class SocketServer_Thread extends Thread {private Socket incoming;private int counter;private Vector v;private String fileDir = .\\KTV\\; //要傳送哪個目錄public SocketServer_Thread(Socket i
int c
Vector v) {incoming = i;counter = c;this.v = v;}public void connectionEnded() { //v.remove(thisincoming);v.remove(this);System.out.println(ID : counter
Connection Ended);}public void run() {try {v.add(this);File fd = new File(fileDir); //某目錄File[] fdlist = fd.listFiles(new TestFileFilter(.mpg)); //選擇要傳的檔案類型try { //String dirarray[] = fd.list();//將要傳的檔案數量給Client端
用以切斷接收DataOutputStream ps = new DataOutputStream(incoming.getOutputStream()); ps.writeInt(fdlist.length);ps.flush(); for (int i = 0; i FileFilter的方法 * * 這個方法表示接受哪些文件 */public boolean accept(File pathname) {return pathname.getName().toLowerCase().indexOf(keyword) = 0;}}}Client端: import java.io. * ;import java.net. * ;import java.util. * ;import java.text. * ;public class ClientTest {public static void main(String[] args) {DataInputStream inputStream = null;DataOutputStream outputStream = null; //**String fileDir = .\\mv\\; //要接收到哪個目錄try {Socket ss = new Socket(127.0.0.1
8821);String savePath = fileDir;int sendnum;int bufferSize = 1000;byte[] buf = new byte[bufferSize];int passedlen = 0;long len = 0;inputStream = new DataInputStream(new BufferedInputStream(ss.getInputStream())); //**outputStream = new DataOutputStream(new BufferedOutputStream(ss.getOutputStream())); //**//取得檔案數量sendnum = inputStream.readInt();System.out.println(要接收 sendnum 個文件);for (int i = 0; i
div
其實只不過是個小事
沒想到你還發一篇文 /div
參考:http://tw.knowledge.yahoo.com/question/question?qid=1712010554492如有不適當的文章於本部落格,請留言給我,將移除本文。謝謝!
留言列表