1.客户端代码:
package com.socket;
import java.awt.EventQueue;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import java.net.Socket;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class TCPClientSocket extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
public JTextField textField;
public JTextField textField_1;
// public JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TCPClientSocket frame = new TCPClientSocket();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TCPClientSocket() {
setTitle("客户端文件传输");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 351, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JLabel lblNewLabel = new JLabel("用户名");
JLabel lblNewLabel_1 = new JLabel("文件路径");
textField = new JTextField();
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setColumns(10);
JButton btnNewButton = new JButton("提交");
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane
.setHorizontalGroup(gl_contentPane
.createParallelGroup(Alignment.LEADING)
.addGroup(
gl_contentPane
.createSequentialGroup()
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.LEADING)
.addGroup(
gl_contentPane
.createSequentialGroup()
.addGap(44)
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.LEADING)
.addComponent(
lblNewLabel_1)
.addComponent(
lblNewLabel))
.addGap(18)
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.LEADING,
false)
.addComponent(
textField_1,
GroupLayout.DEFAULT_SIZE,
143,
Short.MAX_VALUE)
.addComponent(
textField,
GroupLayout.DEFAULT_SIZE,
143,
Short.MAX_VALUE)))
.addGroup(
gl_contentPane
.createSequentialGroup()
.addGap(103)
.addComponent(
btnNewButton)))
.addContainerGap(159, Short.MAX_VALUE)));
gl_contentPane
.setVerticalGroup(gl_contentPane
.createParallelGroup(Alignment.LEADING)
.addGroup(
gl_contentPane
.createSequentialGroup()
.addGap(25)
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.BASELINE)
.addComponent(
lblNewLabel)
.addComponent(
textField,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))
.addGap(38)
.addGroup(
gl_contentPane
.createParallelGroup(
Alignment.BASELINE)
.addComponent(
lblNewLabel_1)
.addComponent(
textField_1,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE))
.addGap(39).addComponent(btnNewButton)
.addContainerGap(105, Short.MAX_VALUE)));
contentPane.setLayout(gl_contentPane);
// String filePath = textField_1.getText();
try {
Socket socket = new Socket(TCPServerSocket.IP, TCPServerSocket.PORT);
if (true) {
btnNewButton.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseClicked(MouseEvent arg0) {
String filePath = textField_1.getText().toString();
String userName = textField.getText().toString();
sendFile(socket, filePath, userName);
}
});
/*
* pp.btnNewButton.addActionListener(new ActionListener() {
*
* public void actionPerformed(ActionEvent e) { sendFile(socket,
* filePath); } });
*/
}
} catch (Exception e) {
// e.printStackTrace();
}
}
private static void sendFile(Socket socket, String filePath, String userName) {
System.out.println(filePath);
DataOutputStream dos = null;
BufferedInputStream bis = null;
// What can BufferedInputStream help ?
// FileInputStream fis = null;
byte[] bytes = new byte[1024];
try {
try {
if (socket.isClosed()) {
socket = new Socket(TCPServerSocket.IP,
TCPServerSocket.PORT);
}
bis = new BufferedInputStream(new FileInputStream(new File(
filePath)));
dos = new DataOutputStream(new BufferedOutputStream(
socket.getOutputStream()));
dos.writeUTF(getFileName(filePath) + "##" + userName);
int length = 0;
while ((length = bis.read(bytes, 0, bytes.length)) > 0) {
dos.write(bytes, 0, length);
dos.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (dos != null)
dos.close();
if (socket != null)
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getFileName(String filePath) {
String[] parts = filePath.split("/");
return parts[parts.length - 1];
}
}
2.服务器端代码:
package com.socket;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
public class TCPServerSocket {
public static final int PORT = 5646; // port
public static final String IP = "127.0.0.1"; // my ip address
/**
* @param args
*/
public static void main(String[] args) {
TCPClientSocket frame = null;
/*
* boolean File f = new File("d:"+File.separator+"receive") ;//
* 实例化File类的对象 f.mkdir();
*/
Socket socket = null;
try {
frame = new TCPClientSocket();
// 创建服务器端
ServerSocket mServerSocket = new ServerSocket(PORT);
System.out.println("Server is already created now ! Waiting for client to connect ...");
// 客户端连接服务器端
socket = mServerSocket.accept();
System.out.println("One client connected to this server successfully !");
// 连接成功,开始传输文件
receiveFile(socket);
} catch (Exception e) {
// e.printStackTrace();
}
}
private static void receiveFile(Socket socket) {
FileOutputStream fos = null;
DataInputStream dis = null;
// buffer起缓冲作用,一次读取或写入多个字节的数据
byte[] buffer = new byte[1024];
try {
try {
// 这里使用DataInputStream,可以调用它的readUTF方法来读取要传输的文件名,客户端使用writeUTF方法将文件名先传输过来
dis = new DataInputStream(socket.getInputStream());
// 首先读取文件名
String oldFileName = dis.readUTF();
int start = oldFileName.lastIndexOf("\\");
int end = oldFileName.lastIndexOf("##");
String fileName = oldFileName.substring(start + 1, end);
String userName = oldFileName.substring(end + 2);
System.out.println(fileName);
System.out.println(userName);
// 文件路径
String fileDir = "E:/receive/";
File userDir = new File(fileDir + userName);
if (!userDir.exists()) {
userDir.mkdirs();
}
String filePath = fileDir + userName + "/" + fileName;
// 利用FileOutputStream来操作文件输出流
fos = new FileOutputStream(new File(filePath));
int length = 0;
/*
* length = dis.read(buffer, 0, buffer.length)
* 一次读入1024个字节的内容到buffer中,length代表实际读入的字节数 fos.write(buffer, 0,
* length) 一次从buffer中的length个字节的内容写入到文件中
* (注:文件大小超过1024B时,length一般为1024,最后一次读取可能小于1024)
*/
while ((length = dis.read(buffer, 0, buffer.length)) > 0) {
fos.write(buffer, 0, length);
fos.flush();
}
} finally {
// 使用完毕后,应关闭输入、输出流和socket
if (dis != null)
dis.close();
if (fos != null)
fos.close();
if (socket != null)
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}