要求上传各种类型文件,就不能使用包装流再进行包装了;
边读编写即可,需要创建数据缓冲区;
复制文件采用System.currentTimeMillis()方法来命名,就不会重复了;
客户端:
import java.io.*;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws IOException {
//7、编写程序,通过TCP协议,完成客户端上传文件到服务器端。
Socket sk = new Socket("192.168.10.103",6666);
OutputStream out = sk.getOutputStream();
//包装输出流;
FileInputStream in = new FileInputStream("Msg.txt");
int len=0;
byte[] bytes = new byte[1024];
while ((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
out.flush();
}
sk.close();
}
}
服务端:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6666);
System.out.println("服务器正常开启!");
//侦听客户端,连接传入之前处于阻塞状态;
Socket sk = ss.accept();
InputStream in = sk.getInputStream();
FileOutputStream out = new FileOutputStream(System.currentTimeMillis() + "副本Msg.txt");
int len=0;
byte[] bytes = new byte[1024];
while ((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
out.flush();
}
ss.close();
}
}