用socket方式传输Image和Sound文件

时间:2022-05-21 06:35:00
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner; public class MediaServer {
private static ServerSocket serverSocket;
private static final int PORT = 12345; public static void main(String[] args) {
System.out.println("Opening port...");
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
System.out.println("Unable to attach to port!");
System.exit(1);
}
do {
try {
Socket connection = serverSocket.accept();
Scanner in = new Scanner(connection.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(connection.getOutputStream());
String message = in.nextLine();
System.out.println(message);
if (message.equalsIgnoreCase("image")) {
sendFile("F://apple.jpg", out);
}
if (message.equalsIgnoreCase("sound")) {
sendFile("F://Matthew.mp3", out);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
} while (true);
} private static void sendFile(String filePath, ObjectOutputStream out) throws Exception {
FileInputStream fileInputStream = new FileInputStream(filePath);
long fileLeng = new File(filePath).length();
int length = (int) fileLeng;
byte[] bytes = new byte[(int) length];
fileInputStream.read(bytes);
fileInputStream.close();
out.writeObject(bytes);
out.flush();
} }
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner; public class MediaClient {
private static InetAddress host;
private static final int PORT = 12345; public static void main(String[] args) {
try {
host = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
System.out.println("Host ID not found.");
System.exit(1);
}
try {
Socket connection = new Socket(host, PORT);
ObjectInputStream in = new ObjectInputStream(connection.getInputStream());
PrintWriter out = new PrintWriter(connection.getOutputStream(), true);
Scanner userIn = new Scanner(System.in);
System.out.println("Enter request (image/sound):");
String message = userIn.nextLine();
while (!message.equalsIgnoreCase("image") && !message.equalsIgnoreCase("sound")) {
System.out.println("Try again:");
System.out.println("Enter request (image/sound):");
message = userIn.nextLine();
}
userIn.close();
out.println(message);
getFile(in, message);
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
} private static void getFile(ObjectInputStream in, String message) throws Exception {
byte[] byteArray = (byte[]) in.readObject();
FileOutputStream outputStream;
if (message.equalsIgnoreCase("image")) {
outputStream = new FileOutputStream("E://apple.jpg");
} else {
outputStream = new FileOutputStream("E://Matthew.mp3");
}
outputStream.write(byteArray);
outputStream.close();
}
}