⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 printermonitor.java

📁 Java网络编程的 客户端和服务器端的源代码 多线程
💻 JAVA
字号:
package PrinterClient;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.StringTokenizer;


 
public class PrinterMonitor extends Frame implements Runnable {
	Panel panel;
	ScrollPane sPanel;
	TextArea textArea;
	Button button1;
	public boolean isLoadDB=false;  
	ServerSocket serverSock;
	public final static int DEFAULT_PORT = 6666;
	Thread MonitorAcceptThread;
	MonitorDeadThread mdthread;
	java.util.Vector clients;//
	private Connection	con = null;
	private Statement	stmt = null;
	public PrinterMonitor() {		
		try {
			if(isLoadDB)
			  connect("jdbc:postgresql:SPSDB", "postgres","postgres"); 	
			jbInit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		serverListen();
	}

	public void connect(String terminal_id, String terminalname, String terminlhost) throws ClassNotFoundException, SQLException {
		Class.forName("org.postgresql.Driver");
		try {
			con = DriverManager.getConnection(terminal_id, terminalname, terminlhost);
		} catch (SQLException e) {
				throw new SQLException(e.getMessage());
		}
	}
	
	public void disconnect() throws SQLException {
		if (stmt != null) {
			stmt.close();
			stmt = null;
		}
		if (con != null) {
			con.close();
			con = null;
		}
	}

	public synchronized ResultSet execQuery(String sql) throws SQLException {
		ResultSet	rs = null;
		if (con == null) {
			throw new SQLException("DB can not connected");
		}
		if (stmt == null) {
			stmt = con.createStatement();
		}
		rs = stmt.executeQuery(sql);
		
		return rs;
	}
	
	public synchronized int execUpdate(String sql) throws SQLException {
		int		result;
		
		if (con == null) {
			throw new SQLException("DB can not connected");
		}
		if (stmt == null) {
			stmt = con.createStatement();
		}
		result = stmt.executeUpdate(sql);		
		return result;
	}
		
	public synchronized void setPrintClient(PrinterThreadDoWith ptd )
	{
		this.clients.add(ptd);
	}
	
	public synchronized void setDeadThreadState()
	{
		Iterator itr=clients.iterator();
		while(itr.hasNext())
		{
			PrinterThreadDoWith ptd=(PrinterThreadDoWith)itr.next();
			ptd.doOffLineCommand();
		}
	}
	
	 
	private void jbInit() {//
		panel = new Panel();
		sPanel = new ScrollPane();
		textArea = new TextArea("server information:\n");
		button1 = new Button("Exit");

		sPanel.add(textArea);

		button1.addActionListener(new java.awt.event.ActionListener() {//
					public void actionPerformed(ActionEvent e) {
						button1_actionPerformed(e);
					}
				});
		panel.add(button1);

		this.addWindowListener(new PrinterFrame_WindowAdapter(this));//
		this.setSize(600, 600);
		this.setLayout(new BorderLayout());
		this.add(sPanel, BorderLayout.CENTER);
		this.add(panel, BorderLayout.SOUTH);
		this.setVisible(true);

	}

	private void button1_actionPerformed(ActionEvent e) {		
		exit();
	}

	public synchronized  void processMsg(String str) {//			
		  textArea.append(java.util.Calendar.getInstance().getTime()+str);
	}	
	
	private void serverListen() {
		try {
			serverSock = new ServerSocket(DEFAULT_PORT);
		} catch (IOException e) {
			processMsg(e.toString());
			processMsg("server failed!\n");
		}
		processMsg("server listening on port:" + DEFAULT_PORT +"\n");
		clients = new java.util.Vector();		
		MonitorAcceptThread = new Thread(this);//
		MonitorAcceptThread.start();
		mdthread=new MonitorDeadThread(this);
		mdthread.start();		
	}

	public void run() {
		try {
			while (true) {
				Socket clientSock = serverSock.accept();
				if(clientSock==null) continue;
				PrinterThreadDoWith ct = new PrinterThreadDoWith(clientSock, this);
				clients.add(ct);// client info				
				processMsg(clientSock.getInetAddress().toString()+" join in\n");
			}
		} catch (IOException e) {
			processMsg(e.toString());
		}
	}
	
	public void exit() {
		try {
			mdthread.stopRun();
			if(isLoadDB)
				disconnect();
			serverSock.close();
		} catch (Exception e) {
		} finally {
			System.exit(0);
		}
	}

	public static void main(String[] args) {
		new PrinterMonitor();
	}
	 
}


class PrinterThreadDoWith extends Thread {
	protected Socket clientSock;
	protected BufferedReader in = null; //received info
	protected PrintWriter out;			//sended info
	PrinterMonitor moniterFrame;
	boolean isTrue = true;
	long startTime;
	String machineName;
	String localIP;
	private boolean isStart=false;

	public PrinterThreadDoWith(Socket Sock, PrinterMonitor cFrame) {
		clientSock = Sock;
		moniterFrame = cFrame;
		machineName=clientSock.getInetAddress().toString();
		try {
			in = new BufferedReader(new InputStreamReader(clientSock
					.getInputStream()));
			out = new PrintWriter(clientSock.getOutputStream());
		} catch (IOException ei) {
			try {
				clientSock.close();
			} catch (IOException ei2) {
			}
			moniterFrame.processMsg(ei.toString());
			return;
		}	
		this.start();		
	}

	public void run() {
		String infor;
		try {
			while (isTrue) {
				infor = in.readLine();
				if(infor != null){
					moniterFrame.processMsg(machineName+"	"+infor+"\n");					
				}
				else
					continue;
				try {
				    doCommand(infor);
					Thread.sleep(100);
				} catch (Exception ex) {
				}
				infor="";
			}
		} catch (IOException e) {
			;
		} finally {
			try {
				moniterFrame.clients.removeElement(clientSock);
				in.close();
				out.close();
				clientSock.close();
			} catch (IOException ei) {
				;
			}
		}

	}


    private void doCommand(String value) throws SQLException 
    {
    	if(value.equals("")||(value==null)) return;
    	StringTokenizer st=new StringTokenizer(value,"#");    	
    	String cmd=st.nextElement().toString();
    	localIP=st.nextElement().toString();    	
		if (cmd.equals("@START"))
		{
			if(moniterFrame.isLoadDB)
				moniterFrame.execUpdate("udpate tablename set flag=true where ip="+localIP);
			moniterFrame.processMsg(" @START  is dowinthing ........... \n");
		}
		if (cmd.equals("@ON"))
		{
			isStart=true;
			startTime=System.currentTimeMillis();
			moniterFrame.processMsg(" @ON  is dowinthing ........... \n");			
		}
		if (cmd.equals("@EXIT"))
		{
			isStart=false;
			stopRun();
			if(moniterFrame.isLoadDB)
				moniterFrame.execUpdate("udpate tablename set flag=false where ip="+localIP);
			moniterFrame.processMsg(" @Exit  is dowinthing ........... \n");
		}
    }
    
	private void stopRun() {
		isTrue = false;
	}
	
	/**/
	public void doOffLineCommand()
	{
		if(isStart){			
			if((System.currentTimeMillis()-startTime)>60000)
			{		
				try{
				if(moniterFrame.isLoadDB)
					moniterFrame.execUpdate("udpate tablename set flag=false where ip="+localIP);
				    moniterFrame.processMsg(" over  Time........... \n");
				isStart=false;
				}catch(Exception exx)
				{}
			}
		}								
	}

	public void sendInformation(String str) {
		try {
			out.println(str);
			out.flush();
		} catch (Exception e) {
			;
		}
	}
}

class PrinterFrame_WindowAdapter extends java.awt.event.WindowAdapter {
	PrinterMonitor MonitorFrame;

	public PrinterFrame_WindowAdapter(PrinterMonitor chatFrame) {
		this.MonitorFrame = chatFrame;
	}

	public void windowClosing(WindowEvent e) {
		MonitorFrame.exit();
	}
}
class MonitorDeadThread extends Thread {
	private boolean isRun=true;
	PrinterMonitor minitorframe;
	MonitorDeadThread(PrinterMonitor frame)
	{
		minitorframe=frame;
	}
	public void stopRun()
	{
		isRun=false;
	}
	public void run()
	{		
		while(isRun)
		{
			minitorframe.setDeadThreadState();
			try{
				 Thread.sleep(100);
		    } catch (Exception e) {}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -