4,356
社区成员
发帖
与我相关
我的任务
分享
package net;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
public class DataSocket {
public static void main(String[] args) throws IOException {
File img1 = new File("C:/Users/Administrator/Pictures/1.jpg");
File img2 = new File("C:/Users/Administrator/Pictures/2.jpg");
Socket socket = new Socket("127.0.0.1", 4848);
String header1 = "a.jpg;" + img1.length();
String header2 = "b.jpg;" + img2.length();
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
FileInputStream in = new FileInputStream(img1);
FileInputStream in2 = new FileInputStream(img2);
byte[] buffer = new byte[8192];
int readBytes = -1;
out.write(header1.getBytes());
out.write("\r".getBytes());
out.flush();
while ((readBytes = in.read(buffer)) != -1) {
out.write(buffer, 0, readBytes);
}
out.flush();
out.write(header2.getBytes());
out.write("\r".getBytes());
out.flush();
while ((readBytes = in2.read(buffer)) != -1) {
out.write(buffer, 0, readBytes);
}
out.flush();
in.close();
in2.close();
out.flush();
out.close();
}
}
//socket传送图片程序
package net;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class DataSocketServer {
final public static int DEFAULT_PORT = 4848;
final public static String FILE_DIR = "D:/";
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(DEFAULT_PORT);
while (true) {
new Thread(new RequestProcessorTask(server.accept())).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class RequestProcessorTask implements Runnable {
private Socket socket = null;
public RequestProcessorTask(Socket socket) {
this.socket = socket;
}
public void run() {
try {
boolean isEnd = false;
BufferedInputStream in = new BufferedInputStream
(socket.getInputStream());
while (!isEnd) {
int d = -1;
StringBuilder header = new StringBuilder();
while ((d = in.read()) != '\r') {
if (d == -1) {
isEnd = true;
break;
}
header.append((char) d);
}
if (!isEnd) {
String[] parms = header.toString().split(";");
FileOutputStream out = new FileOutputStream
(FILE_DIR + parms[0]);
long size = Long.parseLong(parms[1]);
while (size > 0 && (d = in.read()) != -1) {
out.write(d);
size--;
}
out.flush();
out.close();
}
}
in.close();
} catch (IOException e) {
throw new RuntimeException("获取客户端输入流失败", e);
}
}
}
}