客户端:
package TCPCopy;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(),8888);
System.out.println("客户端成功连接服务器");
String filePath ="E:\\A.PNG";
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
byte[]buff = new byte[1024];
int redLen=0;
while((redLen=bis.read(buff))!=-1){
bos.write(buff,0,redLen);
}
bis.close();
bos.close();
socket.close();
System.out.println("文件传给服务器成功");
}
}
服务端:
package TCPCopy;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器端在88888端口监听");
Socket socket = serverSocket.accept();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("F:\\c.jpg"));
byte[] buff = new byte[1024];
int redLen =0;
while((redLen=bis.read(buff))!=-1){
bos.write(buff,0,redLen);
}
bos.close();
bis.close();
socket.close();
serverSocket.close();
System.out.println("文件成功下载");
}
}
|