📄 stockclient.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 StockClient extends JFrame implements ActionListener,Runnable
{
JPanel p1;
JPanel p2;
JPanel p3;
JButton end;
JButton exit;
JButton request;
JRadioButton oneSecButton;
JRadioButton twoSecButton;
JRadioButton threeSecButton;
JRadioButton fourSecButton;
JRadioButton fiveSecButton;
ButtonGroup group;
JTextField enterSymbol;
JTextArea displayPrice;
JLabel lenterSymbol;
JLabel ldisplayPrice;
JLabel lrefreshInterval ;
JToolBar radioTool;
JToolBar enterSymbolTool;
JToolBar displayPriceTool;
JToolBar quitTool;
BorderLayout layout ;
BorderLayout layout2;
BorderLayout layout3;
static boolean serverShutdown=false;
String companySymbol;
static PriceUpdaterThread updater = null;
static Thread requestThread = null;
static Thread thread;
static int refreshInterval = 3000;
static Socket tcpSocket;
static DataInputStream datainputstream;
static DataOutputStream dataoutputstream;
static String serverName ="loopback";
static InetAddress serverIP;
static int serverTCPPort = 1436;
static String serverData="";
StockClient()
{
super("Stock Client" );
//Initialize Panels
p1= new JPanel();
p2= new JPanel();
p3 = new JPanel();
//Initialize Labels
lenterSymbol = new JLabel ("Enter Company Symbol:");
ldisplayPrice = new JLabel ("The latest Stock Price:");
lrefreshInterval = new JLabel("Select the update interval:");
//Initialize toolbars
radioTool = new JToolBar();
enterSymbolTool = new JToolBar();
displayPriceTool = new JToolBar();
quitTool = new JToolBar();
enterSymbolTool.setFloatable(false);
enterSymbolTool.setBorder(BorderFactory.createCompoundBorder
(
BorderFactory.createEtchedBorder(),
BorderFactory.createEmptyBorder(2, 2, 2, 0))
);
displayPriceTool.setFloatable(false);
displayPriceTool.setBorder(BorderFactory.createCompoundBorder
(
BorderFactory.createEtchedBorder(),
BorderFactory.createEmptyBorder(2, 2, 2, 0))
);
quitTool.setFloatable(false);
radioTool.setFloatable(false);
//Initialize text area and text field
displayPrice = new JTextArea(1,0);
enterSymbol = new JTextField("",6);
Font font = new Font(null, Font.ITALIC, 20);
displayPrice.setFont(font);
displayPrice.setForeground(Color.BLUE);
displayPrice.setBackground(Color.LIGHT_GRAY);
displayPrice.setEditable(false);
//Initialize Buttons
end = new JButton();
exit = new JButton();
request = new JButton();
end.setText("END");
exit.setText("EXIT");
request.setText("REQUEST");
end.setMaximumSize(new Dimension(90, 27));
exit.setPreferredSize(new Dimension(82, 27));
request.setPreferredSize(new Dimension(85, 27));
end.addActionListener(this);
exit.addActionListener(this);
request.addActionListener(this);
//Initialize radio button
oneSecButton = new JRadioButton("1 Second");
oneSecButton.setActionCommand("1 Second");
twoSecButton = new JRadioButton("2 Second");
twoSecButton.setActionCommand("2 Second");
threeSecButton = new JRadioButton("3 Second");
threeSecButton.setActionCommand("3 Second");
threeSecButton.setSelected(true);
fourSecButton = new JRadioButton("4 Second");
oneSecButton.setActionCommand("4 Second");
fiveSecButton = new JRadioButton("5 Second");
fiveSecButton.setActionCommand("5 Second");
//Group the radio buttons.
group = new ButtonGroup();
group.add(oneSecButton);
group.add(twoSecButton);
group.add(threeSecButton);
group.add(fourSecButton);
group.add(fiveSecButton);
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(lrefreshInterval);
radioPanel.add(oneSecButton);
radioPanel.add(twoSecButton);
radioPanel.add(threeSecButton);
radioPanel.add(fourSecButton);
radioPanel.add(fiveSecButton);
//Register a listener for the radio buttons.
oneSecButton.addActionListener(this);
twoSecButton.addActionListener(this);
threeSecButton.addActionListener(this);
fourSecButton.addActionListener(this);
fiveSecButton.addActionListener(this);
layout = new BorderLayout(5,5);
layout2 = new BorderLayout(5,5);
layout3 = new BorderLayout(6,6);
//Setting up the layout within the toolbars.
radioTool.add(radioPanel,null);
enterSymbolTool.add(lenterSymbol,null);
enterSymbolTool.add(enterSymbol,null);
enterSymbolTool.add(request,null);
displayPriceTool.add(ldisplayPrice,null);
displayPriceTool.add(displayPrice,null);
p1.setLayout(layout2);
p1.add(radioTool,BorderLayout.NORTH);
p1.add(enterSymbolTool,BorderLayout.CENTER);
p1.add(displayPriceTool,BorderLayout.SOUTH);
p3.add(end);
p3.add(exit);
this.setLayout(layout);
this.add(p1,BorderLayout.NORTH);
this.add(p3,BorderLayout.SOUTH);
setSize(500,295);
setResizable(false);
setVisible(true);
enterSymbol.setEnabled( true );
end.setEnabled(false);
exit.setEnabled(true);
//Create a new TCP socket to the Server.
try
{
System.out.println(":~> Connecting to server...... \n");
tcpSocket = new Socket(serverName,serverTCPPort);
dataoutputstream = new DataOutputStream(tcpSocket.getOutputStream());
}catch(Exception e)
{
System.out.println(":~> Error in creating TCP socket "+e+"\n");
System.out.println(":~> The connection has been refused by the server\n");
};
thread = new Thread(this);
thread.start();
System.out.println(":~> Starting listening thread on TCP Port...... \n");
}
public void actionPerformed( ActionEvent evt)
{
//If the user clicks on REQUEST
if(evt.getSource()==request)
{
if(updater!=null)
updater.stopThread();
end.setEnabled(true);
oneSecButton.setEnabled(false);
twoSecButton.setEnabled(false);
threeSecButton.setEnabled(false);
fourSecButton.setEnabled(false);
fiveSecButton.setEnabled(false);
companySymbol = enterSymbol.getText();
updater = new PriceUpdaterThread(this,refreshInterval,companySymbol);
}
//If the users clicks on EXIT.
if(evt.getSource()==exit)
{
if(!serverShutdown)
disconnectFromServer();
System.exit(0);
}
//If the user clicks on END
if(evt.getSource()==end)
{
disconnectFromServer();
end.setEnabled(false);
updater.stopThread();
updater=null;
enterSymbol.setEnabled(true);
oneSecButton.setEnabled(true);
twoSecButton.setEnabled(true);
threeSecButton.setEnabled(true);
fourSecButton.setEnabled(true);
fiveSecButton.setEnabled(true);
request.setEnabled(true);
}
//Conditions for assigning the refresh interval time selected by the user.
if(evt.getSource()==oneSecButton)
{
refreshInterval = 1000;
}
if(evt.getSource()==twoSecButton)
{
refreshInterval = 2000;
}
if(evt.getSource()==threeSecButton)
{
refreshInterval = 3000;
}
if(evt.getSource()==fourSecButton)
{
refreshInterval = 4000;
}
if(evt.getSource()==fiveSecButton)
{
refreshInterval = 5000;
}
}
//Thread for listening to incoming data from the server.
public void run()
{
try{
//A while loop to read all the incoming messages from the server.
while(thread != null)
{
datainputstream = new DataInputStream(tcpSocket.getInputStream());
System.out.println(":~> Waiting for stock updates from server on TCP port.......... \n");
serverData = datainputstream.readLine();
String price="";
//The first message received from the server.
if(serverData.startsWith("PRICEUPDATE "))
{
System.out.println(":~> Received Price Update from Server...... "+serverData.substring(12)+"\n");
price = serverData.substring(12);
displayPrice.setText(" "+price);
}
else if(serverData.startsWith("END"))
{
serverShutdown=true;
System.out.println(":~> Server Shutdown\n");
displayPrice.setForeground(Color.RED);
displayPrice.setText(" "+"SERVER HAS SHUTDOWN");
updater.QuitConnection();
}
}
}catch(Exception _Exc)
{
System.out.println(":~> Connection Problems....");
}
}
//Method to send TCP messages to the Server.
public void sendTCPMessageToServer(String Message)
{
System.out.println("Sending TCP message");
try {
dataoutputstream.write(new String(Message).getBytes());
}catch(IOException _IoExc) { disconnectFromServer();}
}
//Method to update the server about an explicit disconnect operation.
static private void disconnectFromServer()
{
String message = "END\n";
try {
dataoutputstream.write(new String(message).getBytes());
}catch(IOException _IoExc) {}
}
//Main method.
public static void main( String args[] )
{
/*
if (args.length != 3)
{
System.err.println("Usage: ChatClient <servername> <serverport>. Try again.");
System.exit (-1);
}
serverName = args[0];
serverTCPPort = Integer.parseInt(args[1]);
*/
StockClient application = new StockClient();
// 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 client to request
* for updates in specified intervals of time.
*/
class PriceUpdaterThread implements Runnable
{
Thread thread;
String CMD;
StockClient Parent;
String companySymbol = "";
int refreshInterval = 3000;
String message="";
PriceUpdaterThread(StockClient stockclient,int refreshInterval,String companySymbol)
{
Parent = stockclient;
this.refreshInterval=refreshInterval;
this.companySymbol=companySymbol;
thread = new Thread(this);
thread.start();
}
//Implement the thread
public void run()
{
try {
while(thread != null)
{
message = "REQUEST "+companySymbol+"\n";
Parent.sendTCPMessageToServer(message);
thread.sleep(refreshInterval);
}
}catch(Exception _Exc)
{
System.out.println(":~> Connection problems"+_Exc+"\n");
QuitConnection();
}
}
//A utility method to stop the update thread
public void stopThread()
{
thread.stop();
thread = null;
}
//Method to stop the thread and close the TCP socket for a client.
public void QuitConnection()
{
thread.stop();
thread = null;
try {
Parent.tcpSocket.close();
}catch(IOException _IOExc) { }
Parent.tcpSocket = null;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -