|
题目:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class UploadPicServer {
public static void main(String[] args) throws FileNotFoundException, IOException {
// 创建tcp的socket服务端。
ServerSocket ss = new ServerSocket(10006);
// 获取客户端。
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "......connected");
// 读取客户端发来的数据。
InputStream in = s.getInputStream();
// 将读取到的数据存储到一个文件中。
File dir = new File("d:\\pic");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, ip + ".bmp");
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 获取socket输出流,将上传成功字样发给客户端。
OutputStream out = s.getOutputStream();
out.write("服务器反馈:文件上传成功".getBytes());
fos.close();
s.close();
ss.close();
}
}
import java.net.Socket;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.io.IOException;
import java.io.FileNotFoundException;
public class UploadPicClient {
public static void main(String[] args) throws UnknownHostException, IOException, FileNotFoundException {
// 1. 创建客户端socket。
Socket s = new Socket("localhost", 10006);
// 2. 读取客户端要上传的图片文件。
boolean flag=true;
System.out.println("请输入上传的路径");
File isFile=null;
while(flag){
Scanner sc = new Scanner(System.in);
String path = sc.nextLine();
isFile = new File(path);
if (isFile.isFile()) {
flag=false;
}else{
System.out.println("请输入正确的图片文件路径");
}
}
FileInputStream fis = new FileInputStream(isFile);
// 3. 获取socket输出流,将读到图片数据发送给服务端。
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) != -1) {
out.write(buf, 0, len);
}
// 告诉服务端说:这边的数据发送完毕。让服务端停止读取。
s.shutdownOutput();
// 读取服务端发回的内容。
InputStream in = s.getInputStream();
byte[] bufIn = new byte[1024];
int lenIn = in.read(buf);
String text = new String(buf, 0, lenIn);
System.out.println(text);
fis.close();
s.close();
}
}
|
|