Nhờ mọi người giúp em với, em định làm chương trình truyền file đơn giữa hai máy tính sử dụng giao thức socket. Mọi người có thể nói giúp em làm thế nào không ạ? Em không hiểu làm thế nào để truyền file, chương trình chat thì em làm được. Cám ơn mọi người ạ!!
Lập trình socket chương trình truyền file đơn
1 Like
Truyền file giữa các máy tính trong mạng thì người ta thường nghĩ tới FTP (File transfer protocol).
Mình tìm thấy bộ thư viện này trong C++ hổ trợ FTP
http://www.marshallsoft.com/fce4c.htm
đây là example của nó:
// C/C++ FTP Example
#include <windows.h>
#include <stdio.h>
#include "fce.h"
// download file from FTP server
int Download(char *Host, char *User, char *Pass, char *Folder, char *FileName)
{
int Code;
// connect to server (Host)
Code = fceConnect(0, Host, User, Pass);
// error ? (negative return codes are errors)
if(Code<0) return Code;
// change to proper directory
Code = fceSetServerDir(0, Folder);
if(Code<0) return Code;
// set binary xfer mode fceSetMode(0,'B');
// download the file
Code = fceGetFile(0, FileName);
return Code;
}
2 Likes
Theo mình biết thì socket là một interface, một giao diện giữa các tầng trong mạng, không phải là một giao thức. Mình thấy bên java hỗ trợ khá tốt cái này, nếu truyền theo TCP thì cậu có thể dùng ngay thư viện Socket và luống InputStream, mình nhớ làm theo video trên mạng hướng dẫn làm nhanh lắm, chỉ mất khoảng 5 phút thôi, vì dùng kéo thả nữa. Nhưng mình có thắc mắc khi chạy trong mạng thật vì cái đó chỉ chạy tốt trên máy localhost thôi!
Bạn cho mình xin link video được không? Cám ơn bạn!
import java.io.BufferedInputStream;
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 Main {
public static void main(String[] args) throws IOException {
ServerSocket servsock = new ServerSocket(123456);
File myFile = new File("s.pdf");
while (true) {
Socket sock = servsock.accept();
byte[] mybytearray = new byte[(int) myFile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
}
}
}
The client module
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class Main {
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("127.0.0.1", 123456);
byte[] mybytearray = new byte[1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("s.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
1 Like