要求:
基于TCP协议实现一个向服务器端上传文件的功能
客户端代码:
package Homework2;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args){
System.out.println("客户端已启动");
//1.在本工程下创建一个文件夹,并创建文件,使用这个文件来进行文件传输功能
//当然你也可以在自己电脑上找一个文件直接上传
File file=new File("Example");
file.mkdirs();
File file2=new File("Example\\a.txt");
Socket socket=null;
OutputStream os=null;
FileInputStream fis=null;
try {
//2.创建Socket对象,并得到相应的输出流----以及创建文件输入流
socket=new Socket("127.0.0.1",7000);
os=socket.getOutputStream();
fis=new FileInputStream(file2);
byte[] bs=new byte[1024];
int count=0;
//3.发送文件
while((count=fis.read(bs))!=-1){
os.write(bs, 0, count);
os.flush();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
服务器端代码
package Homework2;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
//2 实现上传文件
public class Server {
public static void main(String[] args){
System.out.println("服务器已启动");
Socket socket=null;
InputStream is=null;
FileOutputStream fos=null;
ServerSocket serverSocket=null;
try {
//1.创建ServerSocket对象,获得Socket对象以及输入流
serverSocket=new ServerSocket(7000);
socket=serverSocket.accept();
is=socket.getInputStream();
//2.接收过来的文件存放位置
fos=new FileOutputStream(new File("Example\\e.txt"));
//3.接收文件
byte[] bs=new byte[1024];
int count=0;
while((count=is.read(bs))!=-1){
fos.write(bs, 0, count);
fos.flush();
}
System.out.println("文件已接收:over!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
运行结果: