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

📄 stockserver.java

📁 a simple socket price updater
💻 JAVA
字号:
/*Name: Vijay Vasant Dixit
 *UTA ID: 1000554524
 *CSE 5306 - Project-1
 */
/*This class represents a Chat Client Which connects to the Server*/
import java.io.*;
import java.awt.*;
import java.util.*;
import java.lang.*;
import java.awt.event.*;
import javax.swing.*;

import java.net.*;

public class StockServer extends JFrame implements ActionListener,Runnable
{
   JPanel p1;
   JPanel p2;
   JButton exit;
   JTextArea display;
   JLabel ldisplay;
   JToolBar displayTool;
   JToolBar exitTool; 
   JScrollPane scrollPanel;
   BorderLayout layout ;
   BorderLayout layout2;
   BorderLayout layout3;
   
   static boolean serverShutdown=false;
   static ServerSocket serversocket;
   static int serverTCPPort = 1436;
   static Thread thread;
   static Socket socket;
   File stockPriceFile ;
   Properties properties;
   static boolean end = false;
   static Socket tcpSocket;
   static DataInputStream datainputstream;
   static DataOutputStream dataoutputstream;
   
   StockServer()
   {        
       super("Stock Server" );
       //Initialize Panels
       p1= new JPanel();
       p2 = new JPanel();
       
       //Initialize text area.
       display = new JTextArea(10,55);
       
       //Initialize Scroll bar
       scrollPanel = new JScrollPane(display);
       
       //Initialize Labels
       ldisplay = new JLabel ("Request Logs");
       
       //Initialize toolbars
       displayTool = new JToolBar();
       displayTool.setFloatable(false);
       displayTool.setBorder(BorderFactory.createCompoundBorder
       (
            BorderFactory.createEtchedBorder(),
            BorderFactory.createEmptyBorder(2, 2, 2, 0))
       );
      
       //Initialize Buttons
       exit = new JButton();
       exit.setText("EXIT");
       exit.setPreferredSize(new Dimension(82, 27));
       exit.addActionListener(this);
       
       // Setting up the layout within the toolbars.
       layout = new BorderLayout(5,5);
       layout2 = new BorderLayout(5,5);
       layout3 = new BorderLayout(6,6); 
       JPanel disp = new JPanel();
       disp.add(ldisplay);
       disp.add(scrollPanel);
       displayTool.add(disp,null);
       
       p1.setLayout(layout2);
       p1.add(displayTool,BorderLayout.CENTER);
       p2.setLayout(layout3);
       p2.add(exit);
        
       this.setLayout(layout);
       this.add(p1,BorderLayout.NORTH);
       this.add(p2,BorderLayout.SOUTH);
       setSize(650,255);
       //setResizable(false);
       setVisible(true);
       exit.setEnabled(true);
       try
		{
    	   display.setText(":~> Creating a server TCP socket... \n");
		   serversocket = new ServerSocket(serverTCPPort);
		}
		catch (IOException _IOExc) { }
		thread = new Thread(this);
		thread.start();
        //Read properties file.
	    properties = new Properties();
	    try {
	        properties.load(new FileInputStream("stockprice.properties"));
	    } catch (IOException e) {
	    }

   }
    
    //To exit the window
     public void actionPerformed( ActionEvent evt)
    {
         //If the users clicks on EXIT.
         if(evt.getSource()==exit)
         {
        	serverShutdown=true; 
            exitServer();
         }
    }
     
    public void run()
 	{
 		while (thread != null)
 		{
 			try
 			{
 				//Accepting a Client Request
 				display.append(":~> Waiting for Client requests on TCP socket... \n");
 				socket = serversocket.accept();
 				//Create a separate TCP thread for each client.
 				display.append(":~> Creating a TCP thread for a new Client request... \n");
 				TCPClientThread clientThread = new TCPClientThread(this, socket);
 			}
 			catch (IOException _IOExc) 
 			{ 
 				display.append(":~> Connection problems... \n");
 				exitServer(); 
 		    }
 		}
 	}
     
    //  Method to send a message to the client over its TCP socket.
	protected void SendMessageToClient(Socket clientsocket, String message)
	{
		try
		{
			dataoutputstream = new DataOutputStream(clientsocket.getOutputStream());
			dataoutputstream.write(new String(message).getBytes());
		}
		catch (IOException _IOExc) { }
	}
	
	//Search the stock price for a company
    int searchStockPrice(String symbol)
	{
		int stockPrice = 0;
		String temp = properties.getProperty(symbol);
		stockPrice = Integer.parseInt(temp);
		return stockPrice;
	}
	
    // Method to disconnect from clients.
	private void exitServer()
	{
        try
		{
	        thread.sleep(5000);
			if (thread != null)
			{
				thread.stop();
				thread = null;
			}
			if (serversocket != null)
			{
	            serversocket.close();
	            serversocket = null;
			}
		}
		catch (Exception _IOExc) { }
		System.exit( 0 );
	}
	
   //Main method.
   public static void main( String args[] )
   {
	  //serverTCPPort = Integer.parseInt(args[0]);
      StockServer application = new StockServer();      
      // The following listener responds to the close event on the window
      application.addWindowListener(
         new WindowAdapter() 
        {
            public void windowClosing( WindowEvent e )
            {            
                System.exit( 0 );
            }
         });
   }
}


/*This class serves the purpose of allowing the server to listen to the TCP socket on a thread created for a particular Client*/ 
class TCPClientThread implements Runnable
{
	Thread thread;
	Socket socket;
	DataInputStream inputstream;
	String CMD;
	StockServer Parent;
	boolean firstUpdate=true;
	String company = "";
	int stockPrice = 0;
	int stockPriceUpdate=0;
	Random generator;
        
	//Initialize an inputStream for listening to TCP socket specific to a Client.
	TCPClientThread(StockServer stockserver,Socket clientsocket)
	{				
		Parent = stockserver;
		socket = clientsocket;	
		generator = new Random(19580427);
		try {	
		inputstream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));		
		}catch(IOException _IOExc) { }
		thread = new Thread(this);
		thread.start();	
	}
	
	//Implement the thread
	public void run()
	{
		while(thread != null)
		{
            try {			
                    Parent.display.append(":~> Listening for stock price update requests on "+socket+"\n");
                    CMD = inputstream.readLine();
                    if(StockServer.serverShutdown!=true)
                    {
		                if(CMD.startsWith("REQUEST "))
		                {
		                    Parent.display.append(":~> Client has requested for stock update on "+CMD.substring(8)+"\n");
		                    if(firstUpdate)
		                    {
		                    	firstUpdate=false;
		                    	stockPrice = Parent.searchStockPrice(CMD.substring(8));
		                    	stockPriceUpdate = stockPrice;
		                    	company=CMD.substring(8);
		                    }
		                    else
		                    {
		                    	if(CMD.substring(8).equals(company))
		                    	{
		                    		stockPriceUpdate = stockPrice + generator.nextInt(10);
		                    		
		                    	}
		                    	else
		                    	{
		                    		stockPrice = Parent.searchStockPrice(CMD.substring(8));	
		                    		stockPriceUpdate = stockPrice;
		                    		company=CMD.substring(8);
		                    	}
		                    }
		                    
		                    String temp = "PRICEUPDATE ";
		            		String updateCMD = temp.concat(Integer.toString(stockPriceUpdate));
		            		updateCMD = updateCMD.concat("\n");
		            		Parent.display.append(":~> Sending update to client on "+socket+"......\n");
		                    Parent.SendMessageToClient(socket, updateCMD);
		                }
		                if(CMD.startsWith("END"))
		                {
		                	Parent.display.append(":~> Client has stopped request for updates\n");
		                }
                    }
                    else
                    {
                    	String temp = "END\n";
                        Parent.SendMessageToClient(socket, temp);
                    }
            }catch(Exception _Exc) 
            {
            	Parent.display.append(":~> Connection Problems....\n");
            	QuitConnection();
            }	
		}
	}
	   
    //Method to stop the thread and close the TCP socket for a client.
	public void QuitConnection()
	{
		thread.stop();
		thread = null;		
		try {
		socket.close();
		}catch(IOException _IOExc) { }
		socket = null;	
	}
}

⌨️ 快捷键说明

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