[java]代码库package socket.file;
import java.io.*;
import java.net.*;
import javax.swing.*;
/**
* 设计界面,在服务器端、客服端间传输图片和文件
*
* @author JH
* @date 2014-9-27
*/
public class Server {
private SocketFrame socketFrame;
private final int port = 5674;
private Socket socket;
public Server() {
try {
ServerSocket server = new ServerSocket(port);
socketFrame = new SocketFrame();
socketFrame.setTitle("Server");
while (true) {
socket = server.accept();
System.out.println("Server : new socket");
socketFrame.setSocket(socket);
new Thread(Server.this::run).start();
}
} catch (IOException e) {
System.out.println("Error Server : " + e);
}
}
private void run() {
while (true) {
socketFrame.receive();
}
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
new Server();
}
}
package socket.file;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.StringTokenizer;
public class Client {
private final int port = 5674;
private String host = "";
private SocketFrame socketFrame;
public Client() {
try {
Socket client = new Socket(host, port);
client.setSoTimeout(100 * 1000);// 最迟响应时间
socketFrame = new SocketFrame();
socketFrame.setSocket(client);
socketFrame.setTitle("Client");
run();
} catch (IOException e) {
System.out.println("Error Server : " + e);
}
}
private void run() {
while (true) {
socketFrame.receive();
}
}
private void getHost() {
while (true) {
host = JOptionPane
.showInputDialog("Enter Server IP : eg. 10.110.124.54");
StringTokenizer token = new StringTokenizer(host, ".");
try {
while (token.hasMoreTokens()) {
Integer.valueOf(token.nextToken());
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Formal Error");
continue;
}
break;
}
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
new Client();
}
}
package socket.file;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.BadLocationException;
public class SocketFrame extends JFrame {
private final int WIDTH = 480;
private final int HEIGHT = 315;
private JTextArea textArea;
private JFileChooser chooser;
private JButton sendFile;
private JButton sendMsg;
private DataOutputStream out;
private DataInputStream in;
public SocketFrame() {
setSize(WIDTH, HEIGHT);
Dimension dime = getToolkit().getScreenSize();
setLocation((dime.width - WIDTH) / 2, (dime.height - HEIGHT) / 2);
createPanel();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void createPanel() {
Container contentPane = getContentPane();
JPanel buttonPanel = new JPanel();
textArea = new JTextArea();
chooser = new JFileChooser();
JScrollPane scrollPane = new JScrollPane(textArea);
sendFile = new JButton("Send File");
sendFile.addActionListener(e -> sendFile());
sendMsg = new JButton("Send Msg");
sendMsg.addActionListener(e -> sendMsg());
buttonPanel.add(sendFile);
buttonPanel.add(sendMsg);
contentPane.add(scrollPane, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
}
});
}
// 发送文件
private void sendFile() {
int option = chooser.showOpenDialog(this);
if (option != JFileChooser.APPROVE_OPTION)
return;
File file = chooser.getSelectedFile();
long length = file.length();
textArea.append("开始发送文件 : " + file.getName() + "\n");
try {
// 发送文件名标记
out.writeUTF(file.getName());
// 发送文件长度标记
out.writeLong(file.length());
// 开启此文件的输入流
DataInputStream input = new DataInputStream(new FileInputStream(
file));
byte[] bytes = new byte[1024];
int len = 0;
int passedLen = 0;
while ((len = input.read(bytes)) != -1) {
out.write(bytes, 0, len);
passedLen += len;
textArea.append("文件已传送 : " + (passedLen * 100 / length) + "%\n");
out.flush();
}
out.flush();
input.close();
textArea.append("发送完成 : " + file.getName() + "\n");
textArea.setCaretPosition(textArea.getLineStartOffset(textArea
.getLineCount() - 1));
} catch (IOException | BadLocationException e) {
System.out.println("From Send() : " + e);
}
}
// 发送消息
private void sendMsg() {
String msg = JOptionPane.showInputDialog("Send Message:");
if (msg.length() == 0)
return;
try {
// 发送消息的标记
out.writeUTF("Message");
out.writeUTF(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
// 接收 分为 消息和文件
public void receive() {
try {
// 类型标记
String InforType = in.readUTF();
switch (InforType) {
case "Message":
String msg = in.readUTF();
textArea.append(msg + "\n");
break;
default:
// 打开个对话框,获取文件保存路径
chooser.setSelectedFile(new File(InforType));
int option = chooser.showSaveDialog(this);
if (option != JFileChooser.APPROVE_OPTION)
return;
String path = chooser.getSelectedFile().getAbsolutePath();
textArea.append("开始接收文件 : " + InforType + "\n");
int fileLength = (int) in.readLong();
byte[] buf = new byte[fileLength];
StringBuffer BufferString = new StringBuffer();
// output-开启文件的输出流
FileOutputStream output = new FileOutputStream(new File(path));
int len = 0;// 一次成功读到的字节
int passedLen = 0;// 目前已读到的字节
while (passedLen < fileLength) {
len = in.read(buf, passedLen, fileLength - passedLen);
if (len > 0) {
passedLen += len;
} else
break;
textArea.append("文件已接收 : " + (passedLen * 100 / fileLength)
+ "%\n");
BufferString.append("" + new String(buf, 0, len) + "\n");
}
output.write(buf);
output.flush();
output.close();
textArea.append("接收完成,文件存为 : " + path + "\n");
// 如果是文本文件 打印到文本区里
InforType = InforType.toLowerCase();
if (InforType.endsWith(".txt") || InforType.endsWith(".html")
|| InforType.endsWith(".htm")
|| InforType.endsWith(".java")
|| InforType.endsWith(".jsp")) {
textArea.append(BufferString.toString() + "\n");
}
// 如果是图片 打开个对话框显示
if (InforType.endsWith(".png") || InforType.endsWith(".gif")
|| InforType.endsWith(".jpg")
|| InforType.endsWith(".bmp")
|| InforType.endsWith(".jpeg")) {
new ImageDialog(path);
}
}
chooser.setSelectedFile(new File("."));;
// 置光标于最后
textArea.setCaretPosition(textArea.getLineStartOffset(textArea
.getLineCount() - 1));
setVisible(true);
} catch (IOException | BadLocationException e) {
e.printStackTrace();
}
}
public void setSocket(Socket socket) {
try {
out = new DataOutputStream(new BufferedOutputStream(
socket.getOutputStream()));
in = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
package socket.file;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* 显示图片
*/
public class ImageDialog extends JDialog {
private ImageIcon img;
private int WIDTH = 500;
private int HEIGHT = 500;
public ImageDialog(String path) {
img =new ImageIcon(path);
scaleImage();
setTitle(path);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(img.getImage(), 5,30 , WIDTH, HEIGHT, null);
}
public void scaleImage() {
int imgWidth = img.getIconWidth();
int imgHeight = img.getIconHeight();
if (imgWidth >= imgHeight) {
HEIGHT = (int) Math.round((imgHeight * WIDTH * 1.0 / imgWidth));
} else {
WIDTH = (int) Math.round((imgWidth * HEIGHT * 1.0 / imgHeight));
}
setSize(WIDTH+5, HEIGHT+30);
System.out.println("scrImg W " + imgWidth + " H " + imgHeight);
System.out.println("Scale W " + WIDTH + " H " + HEIGHT);
/*
* JLabel label = new JLabel(); JPanel panel = (JPanel)
* getContentPane(); panel.setOpaque(false);
*
* label.setBounds(0, 0, WIDTH, HEIGHT);
*
* getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));
*/
}
}