运行结果在(下)部分展示:
Util包:包含数据库工具类DBUtil和封装命令类CommandTransfer
DBUtil类
package Util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
/**
* 数据库工具类
*/
/**
* 获取数据库的连接
* @return
*/
public static Connection getConnection() {
String driverClassName="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/test";
String username="root";
String password="root";
Connection conn=null;
try {
//1.加载MySQL驱动
Class.forName(driverClassName);
//2.获得数据库连接
conn=DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭所有
*/
public static void CloseAll(ResultSet rs,Statement stmt,Connection conn){
try {
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}catch (SQLException e) {
e.printStackTrace();
}
}
}
CommandTransfer类:
package Util;
import java.io.Serializable;
/**
* 客户端与服务器之间传输的指令数据
*/
public class CommandTransfer implements Serializable{
private String cmd;//当前操作的指令
private Object data;//发送的数据
private boolean flag;//操作是否成功
private String result;//返回结果
public CommandTransfer() {
super();
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
Socket包:客户端和服务器相关类
**StartServer类:
package Socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class StartServer {
/**
* 启动服务器
*/
public static void main(String[] args) {
//1.创建ServerSocket对象,并绑定相应的端口
try {
ServerSocket serverSocket = new ServerSocket(8881);
Socket socket=null;
System.out.println("***服务器已经启动****");
while(true){
socket=serverSocket.accept();
ServerThread serverThread=new ServerThread(socket);
serverThread.start();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
ServerThread类:
package Socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.sql.SQLException;
import Entity.FileEntity;
import Entity.User;
import Service.FileService;
import Service.UserService;
import Util.CommandTransfer;
public class ServerThread extends Thread{
private Socket socket=null;
private ObjectInputStream ois=null;
private ObjectOutputStream oos=null;
private UserService us=new UserService();
private FileService fs=new FileService();
public ServerThread(Socket socket) {
this.socket=socket;
}
//run()方法
public void run(){
try {
ois = new ObjectInputStream(socket.getInputStream());
oos=new ObjectOutputStream(socket.getOutputStream());
CommandTransfer transfer=(CommandTransfer)ois.readObject();
try {
transfer=execute(transfer);
} catch (SQLException e) {
e.printStackTrace();
}//执行客户端发送到服务器的指令操作
oos.writeObject(transfer);//响应客户端
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//客户端发送到服务器的指令操作
public CommandTransfer execute(CommandTransfer transfer) throws SQLException, IOException {
String cmd=transfer.getCmd();//获取当前操作的指令
if(cmd.equals("login")){//用户登录
User user=(User)transfer.getData();
boolean Flag=us.login(user);
transfer.setFlag(Flag);
if(Flag){
transfer.setResult("登陆成功!");
}else{
transfer.setResult("用户名或密码不正确,请重新登录!");
}
}else if(cmd.equals("register")){//用户注册
User user=(User)transfer.getData();
us.register(user);
transfer.setFlag(true);
transfer.setResult("注册成功,请登陆!");
}else if(cmd.equals("uploadFile")){
FileEntity file=(FileEntity)transfer.getData();
fs.saveFile(file);//保存文件在数据库中
transfer.setFlag(true);
transfer.setResult("文件上传成功!");
}else if(cmd.equals("downloadFile")){
FileEntity file=(FileEntity)transfer.getData();
// fs.downloadFile(file);//把文件保存在本地
transfer.setFlag(true);
transfer.setResult("文件下载成功!");
}
return transfer;
}
}
StartClient类:
package Socket;
public class StartClient {
/**
* 启动客户端
*/
public static void main(String[] args) {
SocketClient client=new SocketClient();
client.showMainMenu();
}
}
SocketClient类:
package Socket;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import Entity.FileEntity;
import Entity.User;
import Service.FileService;
import Service.UserService;
import Util.CommandTransfer;
public class SocketClient {
Scanner console=new Scanner(System.in);
Socket socket=null;
UserService us=new UserService();
FileService fs=new FileService();
FileEntity file=new FileEntity();
User user=new User();
List<FileEntity> fety=new ArrayList<FileEntity>();
//显示主菜单
public void showMainMenu(){
System.out.println("***欢迎使用imooc文件上传器***");
System.out.println("1.登陆\n2.注册\n3.退出");
System.out.println("****************************");
System.out.println("请选择:");
int choice=console.nextInt();
switch(choice){
case 1:
showLogin();
break;
case 2:
showRegister();
break;
case 3:
System.out.println("再见,感谢您对本系统的支持!");
System.exit(0);
default:
System.out.println("输入有误!");
System.exit(0);
}
}
//注册功能
public void showRegister(){
// User user=new User();
CommandTransfer transfer=new CommandTransfer();
while(true){
System.out.println("请输入用户名:");
String username=console.next();
while(us.queryByUsername(username)){
//该用户名已经被注册,重新填写用户名
System.out.println("该用户名已被注册,请重新输入用户名:");
username=console.next();
}
user.setUsername(username);
System.out.println("请输入密码:");
String password1=console.next();
System.out.println("请再次输入密码:");
String password2=console.next();
//两次密码相同则注册成功
if(!(password1.equals(password2))){
System.out.println("您两次输入的密码不一致!");
System.out.println("**********************");
continue;
}
user.setPassword(password1);
transfer.setCmd("register");
transfer.setData(user);
try {
socket=new Socket("localhost",8881);
sendData(transfer);//将数据发送到服务器
transfer=getData();//获取从服务器返回的数据
System.out.println(transfer.getResult());
System.out.println("*********************");
if(transfer.isFlag()){
break;//注册成功
}else{
System.out.println("注册失败,请重新输入!");
continue;
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
showLogin();//注册完登陆
}
//登陆功能
public void showLogin(){
CommandTransfer transfer=new CommandTransfer();
int count=0;
while(true){
count++;
if(count>3){
System.out.println("您已三次登陆失败,程序退出!");
System.exit(0);
}
System.out.println("请输入用户名:");
user.setUsername(console.next());
System.out.println("请输入密码:");
user.setPassword(console.next());
transfer.setCmd("login");
transfer.setData(user);
try {
socket=new Socket("localhost",8881);
sendData(transfer);//将数据发送到服务器
transfer=getData();//获取从服务器返回的数据
System.out.println(transfer.getResult());
System.out.println("*********************");
if(transfer.isFlag()){
file.setUsername(user.getUsername());
break;//登录成功
}else{
continue;
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// finally{
// closeAll();//结束本次socket通信
// }
}
System.out.println("请上传文件!");
// showUploadFile();// 文件上传
fileMain();//登陆完执行文件上传或下载等操作
}
//与文件相关的函数
public void fileMain(){
String content="*****欢迎来到文件页面*****\n"+
"1.文件上传\n"+
"2.文件下载\n"+
"3.文件更新\n"+
"4.文件删除\n"+
"5.文件查看(查看所有文件)\n"+
"6.文件查看(根据username查看文件)\n"+
"7.文件查看(根据fid查看文件)\n"+
"8.退出imooc文件上传器\n"+
"请输入您的选择:";
while(true){
System.out.println(content);
int choice2=console.nextInt();
switch(choice2){
case 1:
showUploadFile();
break;
case 2:
downloadFile();
break;
case 3:
updateFile();
break;
case 4:
deleteFile();
break;
case 5:
queryAll();
break;
case 6:
queryFileByUsername();
break;//跳出switchcase
case 7:
queryFileByFid();
break;//跳出switchcase
case 8:
System.out.println("您已退出imooc文件上传器!");
System.exit(0);
}
}
}
//根据fid查找文件
public void queryFileByFid() {
System.out.println("请输入要查找文件的[fid]");
int fid=console.nextInt();
try {
FileEntity file=fs.queryFileByFid(fid);
System.out.println("文件[fid]="+fid+"的文件信息如下:");
System.out.println(file.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
//更新文件
public void updateFile(){
System.out.println("请输入要更新文件的[fid]");
int fid=console.nextInt();
try {
FileEntity file=new FileEntity();
file.setFid(fid);
System.out.println("请输入文件名[fname]");
String fname=console.next();
file.setFname(fname);
fs.updateFile(file);
System.out.println("成功更新文件"+fid+"!");
} catch (SQLException e) {
e.printStackTrace();
}
}
//删除文件
public void deleteFile() {
System.out.println("请输入要删除文件的[fid]");
int fid=console.nextInt();
try {
fs.deleteFile(fid);
System.out.println("成功删除文件!");
} catch (SQLException e) {
e.printStackTrace();
}
}
//查看数据库所有文件
public void queryAll() {
System.out.println("****数据库中所有文件如下:****");
try {
fety=fs.queryAll();
for(FileEntity file:fety){
System.out.println(file.toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//查看文件(根据username)
public void queryFileByUsername(){
try {
System.out.println("请输入用户名:");
String username=console.next();
System.out.println("****username="+username+"上传的文件如下:****");
fety=fs.queryFile(username);
for(FileEntity file:fety){
System.out.println(file.toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//下载文件
public void downloadFile() {
FileOutputStream fos=null;
BufferedOutputStream bos=null;
//接下来根据fid选择需要下载的文件
System.out.println("请输入需要下载文件的文件[fid]");
int fileId=console.nextInt();
try {
System.out.println("****您要下载的文件如下:****");
FileEntity file=fs.queryFileByFid(fileId);
System.out.println(file.toString());
//下载
System.out.println("请输入下载路径(如 E:/java学习笔记/fileDemo/1.mp3):");
String filename = console.next();
File desFile=new File(filename);
if(!desFile.exists()){
desFile.createNewFile();//创建文件
}
fos=new FileOutputStream(desFile);
byte[] fcontent=file.getFcontent();
bos=new BufferedOutputStream(fos);
bos.write(fcontent,0,fcontent.length);
CommandTransfer transfer=new CommandTransfer();
transfer.setCmd("downloadFile");
transfer.setData(file);//此时要传送文件
socket=new Socket("localhost",8881);
sendData(transfer);
transfer=getData();
System.out.println(transfer.getResult());
System.out.println("**********************");
} catch (SQLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
bos.close();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
//文件上传
public void showUploadFile() {
System.out.println("请输入文件上传的绝对路径(如e:/java学习笔记/socket学习/1.mp3)");
String path=console.next();
// FileEntity file=null;
FileInputStream fis=null;
BufferedInputStream bis=null;
String filename=path.substring(path.lastIndexOf("/")+1);
try {
fis=new FileInputStream(path);
byte[] fcontent=new byte[fis.available()];
bis=new BufferedInputStream(fis);
bis.read(fcontent);
file.setFname(filename);
file.setFcontent(fcontent);
// file=new FileEntity(user.getUsername(),filename,fcontent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
bis.close();
// fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
CommandTransfer transfer=new CommandTransfer();
transfer.setCmd("uploadFile");
transfer.setData(file);//此时要传送文件
try {
socket=new Socket("localhost",8881);
sendData(transfer);
transfer=getData();
System.out.println(transfer.getResult());
System.out.println("**********************");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally{
// closeAll();
}
}
public void closeAll() {
console.close();
try {
if(socket!=null){
socket.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
public CommandTransfer getData() throws Exception {
ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
CommandTransfer transfer=(CommandTransfer)ois.readObject();
return transfer;
}
public void sendData(CommandTransfer transfer) throws IOException {
ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(transfer);
oos.flush();
}
}
点击查看更多内容
4人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦