Class 2 | Intermediate Java 30-IT-397 |
Implementing Servers
package networking;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import java.io.*;
import java.net.*;
/**
*
* @author default
*/
public class FavoriteDisco extends javax.swing.JFrame {
DefaultListModel model;
ClientSocket client;
/** Creates new form FavoriteDisco */
public FavoriteDisco() {
initComponents();
model = new DefaultListModel();
lstLyrics.setModel(model);
client = new ClientSocket();
}
/** This method is called from within the constructor
to
* initialize the form.
* WARNING: Do NOT modify this code. The
content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
lstLyrics = new javax.swing.JList();
jPanel1 = new javax.swing.JPanel();
lblFavorite = new javax.swing.JLabel();
String[] arrDisco =
new String[5];
arrDisco[0] = "YMCA";
arrDisco[1] = "Yowsah,
Yowsah, Yowsah";
arrDisco[2] = "You Make
Me Feel";
arrDisco[3] = "That's
The Way";
arrDisco[4] = "Stayin
Alive";
cboDisco = new JComboBox(arrDisco);
btnGo = new javax.swing.JButton();
addWindowListener(new
java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jScrollPane1.setViewportView(lstLyrics);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
lblFavorite.setText("What's
your favorite disco?");
jPanel1.add(lblFavorite);
jPanel1.add(cboDisco);
btnGo.setText("Go");
btnGo.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGoActionPerformed(evt);
}
});
jPanel1.add(btnGo);
getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);
pack();
}
private void btnGoActionPerformed(java.awt.event.ActionEvent
evt) {
// Get the song string
String song = (String) cboDisco.getSelectedItem();
// Send this string to the server via the ClientSocket class.
// Get back the artist.
String artist = client.connect(song);
// Add this to our list.
model.addElement(song + " is performed by " + artist);
}
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent
evt) {
System.exit(0);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
new FavoriteDisco().show();
}
// Variables declaration - do not modify
private javax.swing.JList lstLyrics;
private javax.swing.JButton btnGo;
private javax.swing.JComboBox cboDisco;
private javax.swing.JLabel lblFavorite;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
package networking;
import java.io.*;
import java.net.*;
/**
*
* @author default
*/
public class ClientSocket {
String host = "127.0.0.1";
int port = 8089;
/** Creates a new instance of ClientSocket */
public ClientSocket() {
}
public ClientSocket(String host, int port) {
this.host = host;
this.port = port;
}
public String connect(String
song) {
// The StringBuffer will contain our result that we will change to a String
and return.
StringBuffer result = new StringBuffer();
try {
// Create a socket.
Socket socket = new Socket(host, port);
// Create a PrintWriter to send our song title to the server.
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print(song);
out.print("\r\n");
// Tell it to go ahead and send.
out.flush();
// Create a buffered reader and input stream to read the response.
// We can get the input stream from the socket, and we can pass that to
the buffered reader
// constructor.
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
boolean moreData = true;
// Read while we have information to read.
while(moreData) {
// Read a line from the buffered reader.
String line = in.readLine();
// Read the data, or let the loop know we're finished.
if (line == null) {
moreData = false;
} else {
if (line.equals("Connected.")) { /* just digreguard this. */ }
result.append(line);
} // end if.
} // end for.
// Handle exceptions.
} catch (NumberFormatException e) {
System.out.println("Enter the port as a number, please. Message:
" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException caught while attempting connection.
Message: " + e.getMessage());
e.printStackTrace();
}
return result.toString();
}
public static void main(String args[]) {
}
}
package networking;
import java.io.*;
import java.net.*;
/**
*
* @author default
*/
public class DiscoServer {
/** Creates a new instance of DiscoServer */
public DiscoServer() {
}
public static void main(String
args[]) {
String artist = "invalid";
try {
// establish server socket on port 8089.
ServerSocket s = new ServerSocket(8089);
// A continuous loop to accept connections.
boolean blnMore = true;
while (blnMore) {
// Wait for connection from client.
// When we have a connection from a client, this will return a socket object.
Socket incoming = s.accept();
System.out.println("Socket Accepted");
// Get the buffered reader.
BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
// Get a print writer to send output.
PrintWriter out = new PrintWriter(incoming.getOutputStream(), true);
// out.println("Connected.");
// Get data from the client.
boolean complete = false;
String line = in.readLine();
if (line == null) {
// we're finished.
complete = true;
artist = "Complete";
} else {
System.out.println("Line: " + line);
// pardon my if test.
if(line.equals("YMCA")) {
artist = "Village People";
} else if (line.equals("Yowsah, Yowsah, Yowsah")) {
artist = "Chic";
} else if (line.equals("You Make Me Feel")) {
artist = "Sylvester";
} else if (line.equals("That's The Way")) {
artist = "K.C. and the Sunshine Band";
} else if (line.equals("Stayin Alive")) {
artist = "Bee Gees";
} else if (line.equalsIgnoreCase("stop")) {
blnMore = false;
} else {
artist = "Connected";
}
}
// Send the response.
out.print(artist);
out.print("\r\n");
out.flush();
// Close the connection.
incoming.close();
}
} catch (Exception e) {
e.printStackTrace();
}
// Call it again.
DiscoServer.main(args);
}
}
Created by: Brandan Jones December 17, 2001