.:For Network Programming ( SCN 4223 ) Purpose Only:.

AC990856 Page

--»Assignment 5---- Server.java , Application1.java , Frame1.java (Group Assg & consist 2 mmber)

--Server.java (Using package chat !!!)

//Mohd Syafirul bin Ramli 810320145415
//Muhammad Faizal bin Arishah 800107045037

package chat;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Server extends JFrame
{
private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private int counter = 1;

// set up GUI
public Server()
{
super( "Server" );

Container container = getContentPane();

// create enterField and register listener
enterField = new JTextField();
enterField.setEnabled( false );
enterField.addActionListener(

new ActionListener()
{
// send message to client
public void actionPerformed( ActionEvent event )
{
sendData(event.getActionCommand());
}
} // end anonymous inner class

); // end call to addActionListener

container.add( enterField, BorderLayout.SOUTH );

// create displayArea
displayArea = new JTextArea();
container.add( new JScrollPane( displayArea ),BorderLayout.CENTER );

setSize( 300, 300 );
setVisible( true );
}

// set up and run server
public void runServer()
{
// set up server to receive connections;
// process connections
try {

// Step 1: Create a ServerSocket.
server = new ServerSocket( 5050, 100 );

while ( true ) {

// Step 2: Wait for a connection.
waitForConnection();

// Step 3: Get input and output streams.
getStreams();

// Step 4: Process connection.
processConnection();

// Step 5: Close connection.
closeConnection();

++counter;
}
}

// process EOFException when client closes connection
catch ( EOFException eofException ) {
System.out.println( "Client tidak aktif!" );
}

// process problems with I/O
catch ( IOException ioException ) {
ioException.printStackTrace();
}
}

// wait for connection to arrive, then display connection info
private void waitForConnection() throws IOException
{

displayArea.setText( "Waiting Connection...\n" );

// allow server to accept a connection
connection = server.accept();

displayArea.append( "Connection " + counter +
" accepted from : " +
connection.getInetAddress().getHostName() );
}

// get streams to send and receive data
private void getStreams() throws IOException
{
// set up output stream for objects
output = new ObjectOutputStream(
connection.getOutputStream() );

// flush output buffer to send header information
output.flush();

// set up input stream for objects
input = new ObjectInputStream(
connection.getInputStream() );

displayArea.append( "\nI/O stream\n" );
}

// process connection with client
private void processConnection() throws IOException
{
// send connection successful message to client
String message = "<SERVER> Connected...";
output.writeObject( message );
output.flush();

// enable enterField so server user can send messages
enterField.setEnabled( true );

// process messages sent from client
do {

// read message and display it
try {
message = ( String ) input.readObject();
displayArea.append( "\n" + message );
displayArea.setCaretPosition(
displayArea.getText().length() );
}

// catch problems reading from client
catch ( ClassNotFoundException classNotFoundException ) {
displayArea.append( "\nObjek tidak dikenalpasti" );
}

} while ( !message.equals( "CLIENT>>> TERMINATE" ) );
}

// close streams and socket
private void closeConnection() throws IOException
{
displayArea.append( "\nConnection terminated by user" );
enterField.setEnabled( false );
output.close();
input.close();
connection.close();
}

// send message to client
private void sendData( String message )
{
// send object to client
try {
output.writeObject( "<SERVER> " + message );
output.flush();
displayArea.append( "\n<SERVER>" + message );
}

// process problems sending object
catch ( IOException ioException ) {
displayArea.append( "\nError writing object" );
}
}

// execute application
public static void main( String args[] )
{
Server application = new Server();

application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );

application.runServer();
}

} // end class Server


--Application1.java

//Mohd Syafirul bin Ramli 810320145415
//Muhammad Faizal bin Arishah 800107045037


package chat;

import javax.swing.UIManager;
import java.awt.*;

public class Application1 {
boolean packFrame = false;
String host;

//Construct the application
public Application1(String Host) {
this.host = Host;

Frame1 frame = new Frame1(host);
//Validate frames that have preset sizes
//Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
}
else {
frame.validate();
}
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
frame.runClient();
}

//Main method
public static void main(String[] args) {

try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
e.printStackTrace();
}
if (args.length == 0)
{
Application1 app = new Application1("127.0.0.1");
}
else
{
Application1 app = new Application1(args[0]);
}

}
}

 

--Frame1.java
//Mohd Syafirul bin Ramli 810320145415
//Muhammad Faizal bin Arishah 800107045037


package chat;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;


public class Frame1 extends JFrame {
JPanel contentPane;
JScrollPane jScrollPane1 = new JScrollPane();
JTextArea displayArea = new JTextArea();
JTextField txtChat = new JTextField();
JButton btnConnect = new JButton();
JButton btnDisconnect = new JButton();
JTextField txtNick = new JTextField();
JLabel jLabel1 = new JLabel();
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String chatServer;
private Socket client;
JLabel jLabel2 = new JLabel();

public Frame1(String host){
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
this.chatServer = host;
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
//Component initialization
private void jbInit() throws Exception {
//setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
contentPane = (JPanel) this.getContentPane();
jLabel1.setText("Nick");
jLabel1.setBounds(new Rectangle(28, 16, 48, 21));
txtNick.setBounds(new Rectangle(86, 13, 111, 25));
btnDisconnect.setBounds(new Rectangle(315, 13, 102, 26));
btnDisconnect.setText("Disconnect");
btnDisconnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
btnDisconnect_actionPerformed(e);
}
});
btnConnect.setBounds(new Rectangle(223, 14, 84, 25));
btnConnect.setEnabled(false);
btnConnect.setText("Connect");
btnConnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
btnConnect_actionPerformed(e);
}
});
contentPane.setLayout(null);
this.setSize(new Dimension(450, 307));
this.setTitle("Mari Bersembang");
jScrollPane1.setBounds(new Rectangle(27, 50, 387, 200));
txtChat.setBounds(new Rectangle(73, 256, 343, 28));
txtChat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
txtChat_actionPerformed(e);
}
});
jLabel2.setText("Chat :");
jLabel2.setBounds(new Rectangle(27, 262, 54, 19));
contentPane.add(jLabel1, null);
contentPane.add(txtNick, null);
contentPane.add(btnConnect, null);
contentPane.add(btnDisconnect, null);
contentPane.add(jScrollPane1, null);
contentPane.add(txtChat, null);
contentPane.add(jLabel2, null);
jScrollPane1.getViewport().add(displayArea, null);
}
//Overridden so we can exit when window is closed
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
try {
this.closeConnection();
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
System.exit(0);
}
}
public void runClient()
{
// connect to server, get streams, process connection
try {

// Step 1: Create a Socket to make connection
connectToServer();

// Step 2: Get the input and output streams
getStreams();

// Step 3: Process connection
processConnection();

// Step 4: Close connection
closeConnection();
}

// server closed connection
catch ( EOFException eofException ) {
System.out.println( "Server tidak aktif!" );
}

// process problems communicating with server
catch ( IOException ioException ) {
ioException.printStackTrace();
}
}

private void getStreams() throws IOException
{
// set up output stream for objects
output = new ObjectOutputStream(
client.getOutputStream() );

// flush output buffer to send header information
output.flush();

// set up input stream for objects
input = new ObjectInputStream(
client.getInputStream() );

displayArea.append( "\nI/O stream\n" );
}

// connect to server
private void connectToServer() throws IOException
{
displayArea.setText( "Sedang menghubungi server\n" );

// create Socket to make connection to server
client = new Socket(
InetAddress.getByName( chatServer ), 5050 );

// display connection information
displayArea.append( "Berjaya menghubungi : " +
client.getInetAddress().getHostName() );
}

// process connection with server
private void processConnection() throws IOException
{
// enable enterField so client user can send messages
txtChat.setEnabled(true) ;

// process messages sent from server
do {

// read message and display it
try {
message = ( String ) input.readObject();
displayArea.append( "\n" + message );
displayArea.setCaretPosition(
displayArea.getText().length() );
}

// catch problems reading from server
catch ( ClassNotFoundException classNotFoundException ) {
displayArea.append( "\nObjek tidak dikenalpasti" );
}

} while ( !message.equals( "<SERVER> TERMINATE" ) );

} // end method process connection

// close streams and socket
private void closeConnection() throws IOException
{
displayArea.append( "\nHubungan diputuskan" );
output.close();
input.close();
client.close();
}

private void sendData( String message )
{
// send object to server
try {
output.writeObject(message);
output.flush();
displayArea.append( "\n<" + this.txtNick.getText()+">" + message );
}

// process problems sending object
catch ( IOException ioException ) {
displayArea.append( "\nError writing object" );
}
}
void btnConnect_actionPerformed(ActionEvent e) {
}

void txtChat_actionPerformed(ActionEvent e) {
this.sendData(e.getActionCommand()) ;
}

void btnDisconnect_actionPerformed(ActionEvent e) {
try{
this.closeConnection();
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
}

Copyright @2003 Ac990856
U6C3-9,Kolej Perdana.
Tel: 6012-7615174 ;
e-mail: masalapang@hotmail.com.my