TCP/IP Compress/Decompress String
I am trying to compress a string, send it to the client file and have the client decompress the string and output it. all the compression/decompression is handled in the compressedmessage file. I got the client and server file working, but cannot figure out the compressed message file at all. I tried using stringbuilder. I would appreciate any help.
note - the string is in the server.java file
compressed message.java
import java.io.Serializable;
import java.util.ArrayList;
import java.lang.String;
public class CompressedMessage implements Serializable
{ // this instance variable will store the original, compressed and decompressed message
private String message;
public CompressedMessage(String message)
{ // begin by coding this method first - initialise instance variable message with the original message
String message = new String();
}
public String getMessage()
{ /* code this method next - return the value of instance
variable message Have a look at the client and server
code to observe it */
return message;
}
private boolean punctuationChar(String str)
{ // Hint: check if the last character in the string is a punctuation
if(str.charAt(message.length() - 1) == '!' || (message.charAt(message.length() - 1) == '.'))
{
return true;
}else
{
return false;
}
}
private String getWord(String str)
{ // Hint: if last character in string is punctuation then remove
if(str.charAt(message.length() - 1) == '!' || (message.charAt(message.length() - 1) == '.'))
{
str = str(str.substring(str.length()-1));
return str;
}
else
{
return str;
}
}
public void compress(String message)
{
String comDictionary;
//split string into words
String [] newmessage = message.split(delimiter, 2);
List<String> list = Arrays.asList(newmessage);
StringBuilder comDictionary = new StringBuilder();
Iterator<String> iter = newmessage.iterator();
while (iter.hasNext()) {
if (newmessage.length() > 0)
comDictionary.append(" ");
decomDictionary.append(iter.next());
}
}
public void decompress(String message)
{
String decomDictionary;
//split string into words
String [] newmessage = message.split(delimiter, 2);
List<String> list = Arrays.asList(newmessage);
StringBuilder decomDictionary = new StringBuilder();
Iterator<String> iter = newmessage.iterator();
while (iter.hasNext()) {
if (newmessage.length() > 0)
decomDictionary.append(" ");
decomDictionary.append(iter.next());
}
}
}
client.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.Random;
public class P5_Client extends JFrame
{ // variables for the GUI components of the game
Container c;
// this variable will be instantiated to an object of inner private class ButtonHandler
ButtonHandler bHandler;
JButton startButton, rollButton;
JPanel gamePanel, buttonPanel, outputPanel;
JLabel dieImage1, dieImage2;
JTextArea outputArea;
ImageIcon[] dice = {new ImageIcon("blank.gif"), new ImageIcon("die_1.gif"), new ImageIcon("die_2.gif"), new ImageIcon("die_3.gif"), new ImageIcon("die_4.gif"), new ImageIcon("die_5.gif"), new ImageIcon("die_6.gif")};
// socket to communicate with server
Socket socket;
// input and output streams for sending objects to and receiving objects from the server
ObjectInputStream clientInputStream;
ObjectOutputStream clientOutputStream;
public P5_Client()
{ super("P5_Client");
addWindowListener
( new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
// create and add GUI components
c = getContentPane();
c.setLayout(new BorderLayout());
// this panel will contain the text area
outputPanel = new JPanel();
outputPanel.setBackground(Color.WHITE);
// add text area
outputArea = new JTextArea(16,30);
outputArea.setEditable(false);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setFont(new Font("Verdana", Font.BOLD, 11));
outputPanel.add(outputArea);
outputPanel.add(new JScrollPane(outputArea));
c.add(outputPanel, BorderLayout.NORTH);
// this panel will contain the dice images
gamePanel = new JPanel();
gamePanel.setBackground(Color.WHITE);
gamePanel.setLayout(new GridLayout(1,2));
dieImage1 = new JLabel(dice[0], SwingConstants.CENTER);
dieImage2 = new JLabel(dice[0], SwingConstants.CENTER);
gamePanel.add(dieImage1);
gamePanel.add(dieImage2);
c.add(gamePanel, BorderLayout.CENTER);
// this panel will contain the game buttons
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.WHITE);
// add button to remove game rules (and start game)
startButton = new JButton("start game");
bHandler = new ButtonHandler();
startButton.addActionListener(bHandler);
buttonPanel.add(startButton);
// add button to roll dice
rollButton = new JButton("roll dice");
rollButton.addActionListener(bHandler);
rollButton.setEnabled(false);
buttonPanel.add(rollButton);
c.add(buttonPanel, BorderLayout.SOUTH);
setSize(375,425);
setResizable(false);
setVisible(true);
}
void addOutput(String s)
{ // add a message to the text area
outputArea.append(s + "\n");
outputArea.setCaretPosition(outputArea.getText().l ength());
}
void startGame()
{ // game begins - add initial message
outputArea.setText("Make your first roll.\n");
startButton.setEnabled(false);
rollButton.setEnabled(true);
}
void getConnections()
{ try
{ // initialise a socket and get a connection to server
socket = new Socket(InetAddress.getLocalHost(), 6000);
// get input and output streams
clientOutputStream = new ObjectOutputStream(socket.getOutputStream());
clientInputStream = new ObjectInputStream(socket.getInputStream());
// get the compressed game rules from server
CompressedMessage cm = (CompressedMessage)clientInputStream.readObject();
// decompress game rules
cm.decompress();
// output decompressed game rules
addOutput("Rules of the game\n" + cm.getMessage());
}
catch(UnknownHostException e) // thrown by method getLocalHost
{ System.out.println(e);
System.exit(1);
}
catch(IOException e) // thrown by methods getInputStream, getOutputStream
{ System.out.println(e);
System.exit(1);
}
catch(ClassNotFoundException e) // thrown by method readObject
{ System.out.println(e);
System.exit(1);
}
}
void sendDice()
{ try
{ // an object of class Random is required to create random numbers for the dice
Random randomNumbers = new Random();
// get two random numbers between 1 and 6 to represent the dice
int die1 = 1 + randomNumbers.nextInt(6);
int die2 = 1 + randomNumbers.nextInt(6);
// set the appropriate images
dieImage1.setIcon(dice[die1]);
dieImage2.setIcon(dice[die2]);
// send the dice values to the server
clientOutputStream.writeObject(die1);
clientOutputStream.writeObject(die2);
// read message from server
String result = (String)clientInputStream.readObject();
// output message from server
addOutput(result);
/* if the last character of the message is '!' this indicates a
message to end the game */
if(result.charAt(result.length() - 1) == '!')
{ // disable roll button
rollButton.setEnabled(false);
// close input & output streams
clientInputStream.close();
clientOutputStream.close();
// close socket
socket.close();
}
else
// add message to text output area
addOutput("Make a roll.");
}
catch(IOException e) // thrown by methods writeObject, readObject
{ System.out.println(e);
System.exit(1);
}
catch(ClassNotFoundException e) // thrown by method readObject
{ System.out.println(e);
System.exit(1);
}
}
public static void main(String args[])
{ P5_Client gameClient = new P5_Client();
gameClient.getConnections();
}
// this inner class handles all the button events which occur during the game
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{ if(e.getSource() == startButton)
// if the start button is clicked call method startGame
startGame();
else
{ if(e.getSource() == rollButton)
// if the roll button is clicked call method sendDice
sendDice();
}
}
} // end of class ButtonHandler
} // end of class P5_Client
server.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class P5_Server extends JFrame
{ JTextArea outputArea;
ServerSocket serverSocket;
public P5_Server()
{ super("P5_Server");
addWindowListener
( new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
Container c = getContentPane();
c.setLayout(new FlowLayout());
try
{ // get a server socket and bind to port 6000
serverSocket = new ServerSocket(6000);
}
catch(IOException e) // thrown by method ServerSocket
{ System.out.println(e);
System.exit(1);
}
// create and add GUI components
outputArea = new JTextArea(19,30);
outputArea.setEditable(false);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
c.add(outputArea);
c.add(new JScrollPane(outputArea));
setSize(350,350);
setResizable(false);
setVisible(true);
}
void addOutput(String s)
{ // add a message to the text output area
outputArea.append(s + "\n");
outputArea.setCaretPosition(outputArea.getText().l ength());
}
void waitForData()
{ try
{ addOutput("Server is up and waiting for a connection...");
/* client has attempted to get a connection to server, now create a socket
to communicate with this client */
Socket client = serverSocket.accept();
// get input and output streams
ObjectInputStream serverInputStream = new ObjectInputStream(client.getInputStream());
ObjectOutputStream serverOutputStream = new ObjectOutputStream(client.getOutputStream());
addOutput("\nGames Rules\n----------------------------------------");
// game rules
String gameRules = "On each turn you roll two dice.\nEach die has six faces, which contain one, two, three, four, five and six spots, respectively.\nAfter the dice have come to rest, the sum of the spots on the two upward faces is calculated.\nIf, on the first throw, the sum is seven or eleven, you will win, however if the sum is two, three or twelve, you will lose and the server will win.\nIf the sum is four, five, six, eight, nine or ten on the first throw, that sum becomes your point.\nTo win, you must continue to roll the dice until you roll the same point value.\nIf you roll a seven before making your point you will lose.\n";
// output the length of game rules before compression
addOutput("Length of original game rules : " + gameRules.length() + " characters");
// compress game rules
CompressedMessage rules = new CompressedMessage(gameRules);
rules.compress();
// output compressed game rules and length
addOutput("Length of compressed game rules : " + rules.getMessage().length() + " characters\n");
addOutput(rules.getMessage());
// send compressed game rules to client
serverOutputStream.writeObject(rules);
addOutput("Compressed game rules send to client\n\nGame in play\n--------------------------");
// start game
int roll = 1, point = -1;
boolean gameOver = false;
while(!gameOver)
{ // read value of first die
int die1 = (Integer)serverInputStream.readObject();
// read value of second die
int die2 = (Integer)serverInputStream.readObject();
addOutput("From client : " + die1 + "-" + die2);
// add dice
int sum = die1 + die2;
String result = "You rolled: " + sum;
// if this is the first roll
if(roll == 1)
{ switch(sum)
{ // if the total is 7 or 11 the client wins instantly
case 7:
case 11:
result+= " - You Win!";
gameOver = true;
break;
// if the total is 2, 3 or 12 the server wins instantly
case 2:
case 3:
case 12:
result += " - Server Wins!";
gameOver = true;
break;
// if the total is 4, 5, 6, 8, 9, 10 this is the client's point
default:
result += " - You must match this point to win.";
point = sum;
}
}
else
{ // this is not the first roll
if(sum == point)
{ // if the total equals the client's point they win
result += " - You have matched your point - You Win!";
gameOver = true;
}
if(sum == 7)
{ // if the total is 7 the server wins
result += " - You have failed to match your point - Server Wins!";
gameOver = true;
}
}
// increment rolls
roll++;
// send message to client
serverOutputStream.writeObject(result);
addOutput("Message sent to client : " + result);
} // end while
addOutput("GAME OVER");
// close input & output streams
serverInputStream.close();
serverOutputStream.close();
// close socket
client.close();
}
catch(IOException e) // thrown by method readObject, writeObject
{ System.out.println(e);
System.exit(1);
}
catch(ClassNotFoundException e) // thrown by method readObject
{ System.out.println(e);
System.exit(1);
}
}
public static void main(String args[])
{ P5_Server gameServer = new P5_Server();
gameServer.waitForData();
}
}
Re: TCP/IP Compress/Decompress String