ProductsLogo
LogoStudy Documents
LogoAI Grader
LogoAI Answer
LogoAI Code Checker
LogoPlagiarism Checker
LogoAI Paraphraser
LogoAI Quiz
LogoAI Detector
PricingBlogAbout Us
logo

Java Assignment Codes

Verified

Added on  2023/05/30

|52
|5341
|240
AI Summary
Get Java assignment codes for Counter, Traffic Lights and Hilbert Curves. Learn Java programming with Desklib's online library for study material with solved assignments, essays, dissertation etc.

Contribute Materials

Your contribution can guide someone’s learning journey. Share your documents today.
Document Page
Running head: Java Assignment Codes 1
Java Assignment Codes
Student Name
Institution
Location of Institution
Professor’s Name
Date

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Java Assignment Codes 2
Table of Contents
1.1 Question One Part One..............................................................................................................3
1.2 Question One Part Two.............................................................................................................7
1.3 Question Two...........................................................................................................................11
1.4 Question Three.........................................................................................................................19
1.4.1 Main Class........................................................................................................................19
1.4.2 Applet...............................................................................................................................27
1.5 Question Four..........................................................................................................................28
1.5.1 Morse Code Client............................................................................................................28
1.5.2 Morse Code Server...........................................................................................................44
Document Page
Java Assignment Codes 3
1.1 Question One Part One
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package counter;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Keeprawteach
*/
public class Counter {
/**
* @param args the command line arguments
*/
int k, m, counter, sum_counter;
Document Page
Java Assignment Codes 4
public Counter() {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int x = in.nextInt();
DoCalculations(x);
}
void DoCalculations(int n) {
System.out.println("Counter Sum Counter| n | m");
ArrayList<String> combs = new ArrayList<>();
counter = 0;
sum_counter = 0;
for (k = 1; k < n; k++) {
for (m = k + 1; m <= n; m++) {
counter++;
if ((k + m) == n) {
combs.add(k + " + " + m + " = " + n);
}

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Java Assignment Codes 5
if ((k + m) == n) {
sum_counter++;
System.out.println(" " + counter + " " + sum_counter + " " + k + "
" + m);
}else{
System.out.println(" " + counter + " " + k + " " + m);
}
}
}
System.out.println (
"\n\n");
System.out.println (
"Total Combinations: " + String.valueOf(combs.size()));
System.out.println (
"\n\nCombinations:\n");
if (!combs.isEmpty ()
Document Page
Java Assignment Codes 6
) {
for (String comb : combs) {
System.out.println(comb);
}
}
}
public static void main(String[] args) {
// TODO code application logic here
new Counter();
}
}
Document Page
Java Assignment Codes 7
1.2 Question One Part Two
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package counter.part.two;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Keeprawteach
*/
public class CounterPartTwo {
/**
* @param args the command line arguments
*/
int a, b, c, d, e, f, counter, sum_counter;

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Java Assignment Codes 8
public CounterPartTwo() {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int x = in.nextInt();
DoCalculations(x);
}
public static void main(String[] args) {
// TODO code application logic here
new CounterPartTwo();
}
private void DoCalculations(int n) {
System.out.println("Counter | Sum Counter | a | b | c | d | e | f ");
ArrayList<String> combs = new ArrayList<>();
counter = 0;
sum_counter = 0;
for (a = 1; a < n; a++) {
for (b = a + 1; b <= n; b++) {
Document Page
Java Assignment Codes 9
for (c = b + 1; b <= n; b++) {
for (d = c + 1; b <= n; b++) {
for (e = d + 1; b <= n; b++) {
for (f = e + 1; b <= n; b++) {
counter++;
if ((a + b + c + d + e + f) == n) {
combs.add(a + " + " + b + " + " + c + " + " + d + " + " + e + " + " + f + " =
" + n);
}
if ((a + b + c + d + e + f) == n) {
sum_counter++;
System.out.println(counter +" "+sum_counter+" "+a+" "+b+"
"+c+" "+d+" "+e+" "+f );
} else {
System.out.println(counter +" "+a+" "+b+" "+c+" "+d+"
"+e+" "+f );
}
}
}
Document Page
Java Assignment Codes 10
}
}
}
}
System.out.println("\n\n");
System.out.println("Total Combinations: " + String.valueOf(combs.size()));
System.out.println("\n\nCombinations:\n");
if (!combs.isEmpty()) {
for (String comb : combs) {
System.out.println(comb);
}
}
}
}

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Java Assignment Codes 11
1.3 Question Two
package traffic.lights;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class TrafficLights extends JFrame implements ItemListener{
/**
*
*/
private static final long serial_number_version = 1L;
Document Page
Java Assignment Codes 12
//Create buttons for traffic Lights_of_Traffics
private JRadioButton Red_Radio_Button;
private JRadioButton Yellow_Radio_Button;
private JRadioButton Green_Radio_Button;
private ButtonGroup Overal_Radio_Button = new ButtonGroup();
//create class Lights_of_Traffics
private TrafficLights.Light Lights_of_Traffics = new TrafficLights.Light();
public static void main(String[] args)
{
//Create frame
TrafficLights frame = new TrafficLights();
frame.setDefaultCloseOperation(3);
frame.setSize(400, 170);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public TrafficLights()
{
Document Page
Java Assignment Codes 13
setTitle("Traffic Lights");
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout(1));
p1.add(this.Lights_of_Traffics);
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(this.Red_Radio_Button = new JRadioButton("Red"));
p2.add(this.Yellow_Radio_Button = new JRadioButton("Yellow"));
p2.add(this.Green_Radio_Button = new JRadioButton("Green"));
this.Red_Radio_Button.setMnemonic('R');
this.Yellow_Radio_Button.setMnemonic('Y');
this.Green_Radio_Button.setMnemonic('G');
this.Overal_Radio_Button.add(this.Red_Radio_Button);
this.Overal_Radio_Button.add(this.Yellow_Radio_Button);
this.Overal_Radio_Button.add(this.Green_Radio_Button);

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Java Assignment Codes 14
setLayout(new BorderLayout());
add(p1, "Center");
add(p2, "South");
this.Red_Radio_Button.addItemListener(this);
this.Yellow_Radio_Button.addItemListener(this);
this.Green_Radio_Button.addItemListener(this);
this.Green_Radio_Button.setSelected(true);
this.Lights_of_Traffics.turnOnGreen();
}
public void itemStateChanged(ItemEvent e)
{
if (this.Red_Radio_Button.isSelected()) {
this.Lights_of_Traffics.turnOnRed();
}
if (this.Yellow_Radio_Button.isSelected()) {
this.Lights_of_Traffics.turnOnYellow();
}
if (this.Green_Radio_Button.isSelected())
this.Lights_of_Traffics.turnOnGreen();
}
Document Page
Java Assignment Codes 15
class Light extends JPanel
{
/**
*
*/
private static final long serializer = 1L;
private boolean red_color;
private boolean yellow_color;
private boolean green_color;
public Light() {
}
public void turnOnRed() {
this.red_color = true;
this.yellow_color = false;
this.green_color = false;
repaint();
}
public void turnOnYellow()
Document Page
Java Assignment Codes 16
{
this.red_color = false;
this.yellow_color = true;
this.green_color = false;
repaint();
}
public void turnOnGreen()
{
this.red_color = false;
this.yellow_color = false;
this.green_color = true;
repaint();
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Java Assignment Codes 17
if (this.red_color) {
g.setColor(Color.red);
g.fillOval(10, 10, 20, 20);
g.setColor(Color.black);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
g.drawRect(5, 5, 30, 80);
}
else if (this.yellow_color) {
g.setColor(Color.yellow);
g.fillOval(10, 35, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 60, 20, 20);
}
else if (this.green_color) {
g.setColor(Color.green);
g.fillOval(10, 60, 20, 20);
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
Document Page
Java Assignment Codes 18
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
}
else {
g.setColor(Color.black);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
}
}
public Dimension getPreferredSize()
{
return new Dimension(40, 90);
}
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Document Page
Java Assignment Codes 19
1.4 Question Three
1.4.1 Main Class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hilbert.curve;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Java Assignment Codes 20
/**
*
* @author Keeprawteach
*/
public class HilbertCurves extends JApplet {
/**
* @param args the command line arguments
*/
private JTextField OrderTextfield = new JTextField("0", 5);
private HilbertCurve hilbertCurvePanel = new HilbertCurve();
public HilbertCurves() {
JPanel panel = new JPanel();
panel.add(new JLabel("Enter an Order"));
panel.add(OrderTextfield);
Document Page
Java Assignment Codes 21
OrderTextfield.setHorizontalAlignment(SwingConstants.RIGHT);
add(hilbertCurvePanel);
add(panel, BorderLayout.SOUTH);
OrderTextfield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hilbertCurvePanel.setOrder(Integer.parseInt(OrderTextfield.getText()));
}
});
}
private static class HilbertCurve extends JPanel {
private int lenght;
private int order = 1;
private int a, b;
private void setOrder(int order) {
this.order = order;
repaint();
Document Page
Java Assignment Codes 22
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
lenght = Math.min(getWidth(), getHeight());
for (int i = 0; i < order; i++) {
lenght /= 2;
a = lenght / 2;
b = lenght / 2;
Upper(g, order);
}
}
private void Upper(Graphics g, int order) {
if (order > 0) {
Left(g, order - 1);

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Java Assignment Codes 23
lineNewPosition(g, 0, lenght);
Upper(g, order - 1);
lineNewPosition(g, lenght, 0);
Upper(g, order - 1);
lineNewPosition(g, 0, -lenght);
right(g, order - 1);
}
}
private void Left(Graphics g, int order) {
if (order > 0) {
Upper(g, order - 1);
lineNewPosition(g, lenght, 0);
Left(g, order - 1);
lineNewPosition(g, 0, lenght);
Left(g, order - 1);
lineNewPosition(g, -lenght, 0);
Down(g, order - 1);
Document Page
Java Assignment Codes 24
}
}
private void right(Graphics g, int order) {
if (order > 0) {
Down(g, order - 1);
lineNewPosition(g, -lenght, 0);
right(g, order - 1);
lineNewPosition(g, 0, -lenght);
right(g, order - 1);
lineNewPosition(g, lenght, 0);
Upper(g, order - 1);
}
}
private void Down(Graphics g, int order) {
if (order > 0) {
Document Page
Java Assignment Codes 25
right(g, order - 1);
lineNewPosition(g, 0, -lenght);
Down(g, order - 1);
lineNewPosition(g, -lenght, 0);
Down(g, order - 1);
lineNewPosition(g, 0, lenght);
Left(g, order - 1);
}
}
private void lineNewPosition(Graphics g, int deltaX, int deltaY) {
g.drawLine(a, b, a + deltaX, b + deltaY);
a += deltaX;
b += deltaY;
}
}

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Java Assignment Codes 26
public static void main(String[] args) {
// TODO code application logic here
JApplet applet = new HilbertCurves();
applet.init();
applet.start();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hilbert Curves");
frame.getContentPane().add(applet, BorderLayout.CENTER);
frame.setSize(512, 512);
frame.setVisible(true);
}
}
Document Page
Java Assignment Codes 27
1.4.2 Applet
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
</head>
<body>
<applet code="HilbertCurves.class" width="250" height="50"></applet>
</body>
</html>
Document Page
Java Assignment Codes 28
1.5 Question Four
1.5.1 Morse Code Client
package NetworkedMorseCode_client;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Java Assignment Codes 29
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/*
@author Keeprawteach
*/
public class ClientTest {
public static void main(String[] args) {
ClientApp application;
if (args.length == 0) {
application = new ClientApp("127.0.0.1");
} else {
application = new ClientApp(args[0]);
}
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setResizable(false);
Document Page
Java Assignment Codes 30
application.runClient();
}
private static class ClientApp extends JFrame {
private JTextField enterField;
private JTextArea displayArea;
private JTextArea notificationArea;
private JScrollPane notices;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String chatServer;
private String name = "";
private Socket client;
private Boolean openConnection;
final private Character[] characters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.',
',', ':', '?', '\'', '-', '/', '"', '@', '='};
Document Page
Java Assignment Codes 31
final private String[] codes = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
"..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
"-----", ".-.-.-", "--..--", "---...", "..--..", ".----.", "-....-", "-..-.",
".-..-.", ".--.-.", "-...-"};
private Map<Character, String> encodeMorse;
private Map<String, Character> decodeMorse;
public ClientApp(String host) {
super("Happiness Enchancer 2.0");
chatServer = host;
while ((name.length() == 0) || (name.replace(" ", "").length() == 0)) {
name = JOptionPane.showInputDialog("Please enter your display name:");
}
enterField = new JTextField();
enterField.setEditable(false);
enterField.addActionListener(
new ActionListener() {

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Java Assignment Codes 32
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equalsIgnoreCase("terminate")) {
sendData("\\quit");
openConnection = false;
} else {
sendData(convertToMorse(event.getActionCommand()));
}
enterField.setText("");
}
}
);
this.addWindowListener(
new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
if (openConnection) {
Document Page
Java Assignment Codes 33
sendData("\\quit");
openConnection = false;
}
dispose();
System.exit(1);
}
}
);
}
}
);
add(enterField, BorderLayout.NORTH);
displayArea = new JTextArea();
displayArea.setEditable(false);
add(new JScrollPane(displayArea), BorderLayout.CENTER);
notificationArea = new JTextArea();
notificationArea.setEditable(false);
notificationArea.setBackground(Color.LIGHT_GRAY);
Document Page
Java Assignment Codes 34
notificationArea.setForeground(Color.DARK_GRAY);
notices = new JScrollPane(notificationArea);
notices.setPreferredSize(new Dimension(800, 150));
add(notices, BorderLayout.SOUTH);
setSize(800, 600);
setVisible(true);
openConnection = true;
encodeMorse = new TreeMap<>();
decodeMorse = new TreeMap<>();
for (int i = 0; i < characters.length; i++) {
encodeMorse.put(characters[i], codes[i]);
decodeMorse.put(codes[i], characters[i]);
}
}
public void runClient() {
Boolean socketConnected = false;
try {

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Java Assignment Codes 35
if (socketConnected = connectToServer()) {
getStreams();
processConnection();
}
} catch (EOFException eofException) {
displayNotice("Client terminated connection");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
if (socketConnected) {
closeConnection();
}
}
}
private boolean connectToServer() throws IOException {
displayNotice("Welcome " + name + "!");
try {
Document Page
Java Assignment Codes 36
client = new Socket(InetAddress.getByName(chatServer), 61000);
} catch (IOException e) {
displayNotice("Server connection could not be established");
return false;
}
displayNotice("Connected to: " + client.getInetAddress().getHostName());
return true;
}
private void getStreams() throws IOException {
output = new ObjectOutputStream(client.getOutputStream());
output.writeObject(name);
output.flush();
input = new ObjectInputStream(client.getInputStream());
displayNotice("Got I/O streams");
}
Document Page
Java Assignment Codes 37
private void processConnection() throws IOException {
setTextFieldEditable(true);
int newLine;
while (openConnection) {
try {
message = (String) input.readObject();
newLine = message.indexOf('\n');
displayMessage(message.substring(0, newLine));
displayMessage(" " + convertToText(message.substring(newLine + 1)));
} catch (ClassNotFoundException classNotFoundException) {
displayNotice("Unknown object type received");
}
}
}

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Java Assignment Codes 38
private void closeConnection() {
displayNotice("Closing connection");
setTextFieldEditable(false);
try {
output.close();
input.close();
client.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
private void sendData(String message) {
try {
output.writeObject(message);
output.flush();
} catch (IOException ioException) {
displayNotice("Error writing object");
}
Document Page
Java Assignment Codes 39
}
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
displayArea.append(messageToDisplay + "\n");
}
}
);
}
private void displayNotice(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
notificationArea.append(messageToDisplay + "\n");
}
}
);
}
Document Page
Java Assignment Codes 40
private void setTextFieldEditable(final boolean editable) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
enterField.setEditable(editable);
}
}
);
}
private String convertToMorse(String encodeMessage) {
String[] tempWords = encodeMessage.split(" ");
Character tempChar;
StringBuilder codedString = new StringBuilder();
for (String token : tempWords) {
for (int i = 0; i < token.length(); i++) {
tempChar = Character.toLowerCase(token.charAt(i));

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Java Assignment Codes 41
if (encodeMorse.containsKey(tempChar)) {
codedString.append(encodeMorse.get(tempChar));
} else {
codedString.append(token.charAt(i));
}
if (i != (token.length() - 1)) {
codedString.append('/');
}
}
codedString.append("//");
}
displayNotice(" Your Encoded Message is:\n "
+ codedString.toString() + "\n");
return codedString.toString();
}
private String convertToText(String decodeMessage) {
Document Page
Java Assignment Codes 42
String[] tempWords = decodeMessage.split("//");
String[] tempString;
StringBuilder decodedString = new StringBuilder();
Boolean capNext = true;
for (String token : tempWords) {
tempString = token.split("/");
for (String code : tempString) {
if (decodeMorse.containsKey(code)) {
if (capNext) {
decodedString.append(Character.toUpperCase(decodeMorse.get(code)));
capNext = false;
} else {
decodedString.append(decodeMorse.get(code));
}
if (code.equals(".-.-.-") || code.equals("..--..") || code.equals('!')) {
capNext = true;
}
} else {
decodedString.append(code);
Document Page
Java Assignment Codes 43
}
}
decodedString.append(" ");
}
return decodedString.toString();
}
}
}

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Java Assignment Codes 44
1.5.2 Morse Code Server
package NetworkedMorseCode_server;
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
Document Page
Java Assignment Codes 45
public class ServerTest
{
public static void main( String[] args )
{
ServerApp application = new ServerApp();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.execute();
}
private static class ServerApp extends JFrame {
private JTextArea displayArea;
private ServerSocket server;
private ExecutorService runChat;
private List<chatClient> clients;
public ServerApp() {
super("Aurora Server");
runChat = Executors.newCachedThreadPool();
clients = new ArrayList<>();
Document Page
Java Assignment Codes 46
try {
server = new ServerSocket(12345, 100);
} catch (IOException ioException) {
ioException.printStackTrace();
}
displayArea = new JTextArea();
displayArea.setEditable(false);
displayArea.setBackground(Color.BLACK);
displayArea.setForeground(Color.GREEN);
add(new JScrollPane(displayArea), BorderLayout.CENTER);
setSize(600, 300);
setVisible(true);
displayMessage("Morse Code server started");
}
public void execute() {

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Java Assignment Codes 47
while (clients.size() < 100) {
try {
clients.add(new chatClient(server.accept(), clients.size()));
displayMessage("Connection " + clients.size() + " received from: "
+ clients.get(clients.size() - 1).connection.getInetAddress().getHostName());
runChat.execute(clients.get(clients.size() - 1));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
private void displayMessage(final String messageToDisplay) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
displayArea.append(messageToDisplay + "\n");
}
Document Page
Java Assignment Codes 48
}
);
}
private void sendData(String message) {
try {
for (chatClient client : clients) {
client.output.writeObject(message);
client.output.flush();
}
} catch (IOException ioException) {
displayMessage("Error writing object");
}
}
private void removeClient(int removeClientNum) {
displayMessage("Removing client " + removeClientNum);
clients.remove(removeClientNum);
if ((clients.size() > 0) && (removeClientNum < clients.size())) {
for (chatClient client : clients) {
if (client.clientNumber != 0) {
Document Page
Java Assignment Codes 49
client.clientNumber -= 1;
}
}
}
displayMessage("Clients renumbered");
}
private class chatClient implements Runnable {
private ObjectOutputStream output;
private ObjectInputStream input;
private Socket connection;
private int clientNumber;
private String clientName;
private Boolean openConnection;
public chatClient(Socket socket, int number) {
connection = socket;
clientNumber = number;
try {
getStreams();

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Java Assignment Codes 50
} catch (IOException ioException) {
ioException.printStackTrace();
}
openConnection = true;
}
private void getStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
try {
clientName = (String) input.readObject();
} catch (ClassNotFoundException classNotFoundException) {
}
displayMessage("Got I/O streams for client " + clientName + "(" + clientNumber + ")");
}
private void processConnection() throws IOException {
String message = "Client connection " + clientNumber + " successful";
while (openConnection) {
try {
Document Page
Java Assignment Codes 51
message = (String) input.readObject();
if (message.equalsIgnoreCase("\\quit")) {
openConnection = false;
} else {
sendData(clientName + "\n" + message);
}
} catch (ClassNotFoundException classNotFoundException) {
sendData("Unknown object type received");
}
}
}
private void closeConnection() {
displayMessage("\nTerminating connection for client " + clientNumber + "\n");
try {
output.close();
input.close();
connection.close();
} catch (IOException ioException) {
ioException.printStackTrace();
Document Page
Java Assignment Codes 52
}
}
public void run() {
try {
processConnection();
} catch (EOFException eofException) {
sendData("\nServer terminated connection for client " + clientNumber + "\n");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
closeConnection();
removeClient(clientNumber);
Thread.currentThread().interrupt();
}
}
}
}
}
1 out of 52
[object Object]

Your All-in-One AI-Powered Toolkit for Academic Success.

Available 24*7 on WhatsApp / Email

[object Object]