第四次验收:面向对象与多线程综合实验之网络编程与多线程版本
面向对象与多线程综合实验是一次大项目,总共分为4个部分进行验收,我将分成四个部分展示4个版本的项目工程。希望看到本文章的你,对你有所收获。
文章目录
档案管理系统简介
档案管理系统:用于规范档案文件管理,构建档案资源信息共享服务平台,为用户提供完整的档案管理和网络查询功能。
• 系统是一个基于C/S的GUI应用程序
• 使用Java SE开发
• 综合运用面向对象编程的相关知识
系统环境
系统开发环境:JavaSE-12
集成开发工具:Eclipse Java 2019-06
GUI开发插件:Window Builder
数据库:MySQL Server 8.0.22+Navicat Premium 12
系统功能
基于TCP的Java Socket连接过程
建立连接的过程
• 服务器端生成一个ServerSocket实例对象,随时监听客户端的连接请求
• 客户端生成一个Socket实例对象,并发出连接请求
• 服务器端通过accept()方法接收到客户端的请求后,新建一个Socket与之进行连接
• 通信都是通过一对InputStream和OutputStream进行的
• 通信结束后,两端分别关闭对应的Socket
基于TCP的Socket编程
• 由Socket获得的输入流与输出流,可设为ObjectInputStream和
ObjectOutputStream
• 需要设计客户端与服务器端的通信规则,让通信双方明白将要发送的是什么。例如收到>>>CLIENT_FILE_UP,表明客户端要上传档案文件
• 可设计相应的类传送文件的相关属性信息,该类必须可序列化
• 客户端可以直连数据库;也可将所有请求都提交服务器,由服务器连接
数据库,处理相关操作,把结果返还给客户端
多线程Socket编程
解决方案
• 引入多线程
• 将与Client通信的任务为派给另一个线程
以下是本篇文章正文内容,下面案例可供参考
具体实现
1.服务器端
Server.java
数据库加载放在服务器端。
代码如下(示例):
package Internet1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Enumeration;
import javax.swing.JTextArea;
import MSystem.DataProcessing;
import MSystem.Doc;
import MSystem.User;
public class Server extends ServerSocket
{
private static JTextArea displayArea; // display information to user
private static ObjectOutputStream output; // output stream to client
private static ObjectInputStream input; // input stream from client
private static Socket connection; // connection to client
String uploadpath="..\\ManagementSystem-v4(Server)\\uploadfile\\";
Timestamp timestamp=new Timestamp(System.currentTimeMillis());
// set up GUI
private static final int SERVER_PORT =12345;
public Server()throws IOException, SQLException
{
// super( "Server" );
super(SERVER_PORT);
try {
while (true) {
Socket socket = accept();
System.out.println("Connection "+ " received from: "+socket.getInetAddress().getHostName() );
CreateServerThread a=new CreateServerThread();
a. ServerThread(socket);//当有请求时,启一个线程处理
}
}catch (IOException e) {
}finally {
close();
}
}
/* enterField = new JTextField(); // create enterField
enterField.setEditable( false );
enterField.addActionListener(
new ActionListener()
{
// send message to client
public void actionPerformed( ActionEvent event )
{
sendData( event.getActionCommand() );
enterField.setText( "" );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
/* getContentPane().add( enterField, BorderLayout.NORTH );
displayArea = new JTextArea(); // create displayArea
getContentPane().add( new JScrollPane( displayArea ), BorderLayout.CENTER );
setSize( 300, 150 ); // set size of window
setVisible( true ); // show window
// end Server constructor*/
class CreateServerThread extends Thread {
//private Socket client;
/* private BufferedReader bufferedReader;
private PrintWriter printWriter;*/
public void ServerThread(Socket s)throws IOException {
connection = s;
output = new ObjectOutputStream(connection.getOutputStream());
input = new ObjectInputStream(connection.getInputStream());
output.flush();
//printWriter =new PrintWriter(client.getOutputStream(),true);
System.out.println("\nGot I/O streams\n");
System.out.println("Client(" + getName() +") come in...");
start();
}
// set up and run server
/* public void run()
{
try // set up server to receive connections; process connections
{
server = new ServerSocket( 12345, 100 ); // create ServerSocket
while ( true )
{
try
{
waitForConnection(); // wait for a connection
getStreams(); // get input & output streams
processConnection(); // process connection
} // end try
catch ( EOFException eofException )
{
displayMessage( "\nServer terminated connection" );
} // end catch
finally
{
closeConnection(); // close connection
counter++;
} // end finally
} // end while
} // end try
catch ( IOException ioException )
{
ioException.printStackTrace();
} // end catch
} // end method runServer
// wait for connection to arrive, then display connection info
private void waitForConnection() throws IOException
{
displayMessage( "Waiting for connection\n" );
connection = server.accept(); // allow server to accept connection
displayMessage( "Connection " + counter + " received from: " +
connection.getInetAddress().getHostName() );
} // end method waitForConnection
// get streams to send and receive data
private void getStreams() throws IOException
{
// set up output stream for objects
output = new ObjectOutputStream( connection.getOutputStream() );
output.flush(); // flush output buffer to send header information
// set up input stream for objects
input = new ObjectInputStream( connection.getInputStream() );
displayMessage( "\nGot I/O streams\n" );
} // end method getStreams
// process connection with client*/
public void run()
{
String message = "Connection successful";
System.out.println( message ); // send connection successful message
// enable enterField so server user can send messages
// setTextFieldEditable( true );
do // process messages sent from client
{
try {
message = (String)input.readObject();
//displayMessage( "\n" + message ); // display message
System.out.println("Client(" + getName() +") say: " + message);
if(message.equals("CLIENT>>> CLIENT_LOGIN")) {
String name = null;
name = (String)input.readObject();
String password = null;
password = (String)input.readObject();
if(DataProcessing.search(name, password)!=null) {
sendData("CLIENT_LOGIN_TRUE");
String role=DataProcessing.getrole(name);
output.writeObject(role);
output.flush();
}
else {
sendData("CLIENT_LOGIN_FALSE");
}
} else if(message.equals("CLIENT>>> CLIENT_CHANGESELF")) {
String name=(String)input.readObject();
String password=(String)input.readObject();
String role=(String)input.readObject();
try {
if(DataProcessing.updateUser(name, password, role))
{
sendData("CLIENT_CHANGESELF_TRUE");
output.writeObject(password);
output.flush();
}
else sendData("CLIENT_CHANGESELF_FAlSE");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(message.equals("CLIENT>>> CLIENT_DELETEUSER")) {
String name=(String)input.readObject();
try {
if(DataProcessing.deleteUser(name))
sendData("CLIENT_DELETEUSER_TRUE");
else
sendData("CLIENT_DELETEUSER_FALSE");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(message.equals("CLIENT>>> CLIENT_INSERTUSER")) {
String name=(String)input.readObject();
String password=(String)input.readObject();
String role=(String)input.readObject();
try {
if(DataProcessing.insertUser(name, password, role))
sendData("CLIENT_INSERTUSER_TRUE");
else
sendData("CLIENT_INSERTUSER_FALSE");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(message.equals("CLIENT>>> CLIENT_UPDATEUSER")) {
String name=(String)input.readObject();
String password=(String)input.readObject();
String role=(String)input.readObject();
try {
if(DataProcessing.updateUser(name, password, role))
sendData("CLIENT_UPDATEUSER_TRUE");
else
sendData("CLIENT_UPDATEUSER_FALSE");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(message.equals("CLIENT>>> CLIENT_UPLOADFILE")) {
String ID=(String)input.readObject();
String creator=(String)input.readObject();
String description=(String)input.readObject();
String filename=(String)input.readObject();
Long filelength=input.readLong();
byte[] buffer=new byte[1024];
int l=0;
FileOutputStream out=new FileOutputStream(new File(uploadpath+filename));
System.out.println("开始接收文件<"+filename+">,文件大小为<"+filelength+">");
while(true) {
int read=input.read(buffer,0,buffer.length);
if(read==-1) break;
l+=read;
System.out.println("接收文件的进度"+100.0*l/filelength+"%...");
out.write(buffer,0,read);
out.flush();
if(l>=filelength)break;
}
out.close();
System.out.println("接收文件<"+filename+">成功");
try {
if(DataProcessing.insertDoc(ID, creator, timestamp, description, filename))
sendData("CLIENT_UPLOADFILE_TRUE");
else
sendData("CLIENT_UPLOADFILE_FALSE");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(message.equals("CLIENT>>> CLIENT_DOWNLOADFILE")) {
sendData("CLIENT_DOWNLOADFILEING");
String ID=(String)input.readObject();
String filename = DataProcessing.searchDoc(ID).getFilename();
File file=new File(uploadpath+filename);
long fileLength=file.length();
output.writeObject(filename);
output.flush();
output.writeLong(fileLength);
output.flush();
FileInputStream in=new FileInputStream(file);
byte[] buffer=new byte[1024];
int length=in.read(buffer,0,buffer.length);
while(length>0) {
output.write(buffer,0,length);
output.flush();
}
in.close();
}else if(message.equals("CLIENT>>> CLIENT_LISTUSER")) {
Enumeration<User> e=DataProcessing.getAllUser();
String[][] rowData=new String[50][3];
User user=null;
int x=0;
while(e.hasMoreElements()) {
user=e.nextElement();
rowData[x][0]=user.getName();
rowData[x][1]=user.getPassword();
rowData[x][2]=user.getRole();
x++;
}
sendData("CLIENT_LISTUSER");
output.writeInt(x);
output.flush();
for(int j=0;j<x;j++) {
for(int a=0;a<3;a++) {
output.writeObject(rowData[j][a]);
output.flush();
}
}
}
else if(message.equals("CLIENT>>> CLIENT_LISTDOC")) {
Enumeration<Doc> e=DataProcessing.getAllDocs();
String[][] rowData=new String[50][5];
Doc doc=null;
int i=0;
while(e.hasMoreElements()) {
doc=e.nextElement();
rowData[i][0]=doc.getID();
rowData[i][1]=doc.getCreator();
rowData[i][2]=doc.getTimestamp().toString();
rowData[i][3]=doc.getFilename();
rowData[i][4]=doc.getDescription();
i++;
}
sendData("CLIENT_LISTDOC");
output.writeInt(i);
output.flush();
for(int j=0;j<i;j++) {
for(int i1=0;i1<=4;i1++) {
output.writeObject(rowData[j][i1]);
output.flush();
}
}
}
// end try
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while ( !message.equals( "CLIENT>>> TERMINATE" ) );
System.out.println("Client(" + getName() +") exit!");
}
// close streams and socket
@SuppressWarnings("unused")
private void closeConnection()
{
//displayMessage( "\nTerminating connection\n" );
// setTextFieldEditable( false ); // disable enterField
try
{
output.close(); // close output stream
input.close(); // close input stream
connection.close(); // close socket
} // end try
catch ( IOException ioException )
{
ioException.printStackTrace();
} // end catch
} // end method closeConnection
// send message to client
private void sendData( String message )
{
try // send object to client
{
output.writeObject( "SERVER>>> " + message );
output.flush(); // flush output to client
System.out.println( "\nSERVER>>> "+"Client(" + getName() +"): " + message );
} // end try
catch ( IOException ioException )
{
displayArea.append( "\nError writing object" );
} // end catch
} // end method sendData
// manipulates displayArea in the event-dispatch thread
/*private void di