Java This is a server & client based program. This program’s Server will start b
ID: 3863966 • Letter: J
Question
Java
This is a server & client based program.
This program’s Server will start by opening a ServerSocket and awaits a connection, but with two Clients. The Clients that connect will both be running the exact same code from the same class. To be able to tell which Client will receive what data, the Server will need to keep track of them by creating two different Sockets for the Clients to connect to. In a linear fashion, the Server will accept a connection from two different Clients, and then set up an InputStream and an OutputStream for each one. Using the individual streams, you will then send an ID to each client individually. One Client will receive one ID, and the other Client will receive the other. Both Clients will print out the ID they receive.
Note: Both clients must connect to the Server before the IDs are sent. They must both be connected to the Server simultaneously.
To summarize, your program should do the following:
Create a Server class. This class should have two Sockets; one for each Client.
Create a Client class. This class should be run twice to create two Clients.
Have the Server accept connections from each run of the Client class.
Setup an InputStream and an OutputStream for each Client.
Send an ID to each client – these IDs must be unique.
Have the Client print out the ID it received to the console.
Close everything and disconnect both clients.
Explanation / Answer
Server.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server { public static void main(String[] args) throws Exception {
System.out.println("The server is running.");
int clientNumber = 0;
ServerSocket listener = new ServerSocket(9999);
try {
while (true) {
new Square(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
}
private static class Square extends Thread {
private Socket socket;
private int clientNumber;
public Square(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
log("New connection with client# " + clientNumber + " at " + socket);
}
public void run() {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Send a welcome message to the client.
out.println("Hello, you are client #" + clientNumber + ".");
} catch (IOException e) {
log("Error handling client# " + clientNumber + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what's going on?");
}
log("Connection with client# " + clientNumber + " closed");
}
}
/**
* Logs a simple message. In this case we just write the
* message to the server applications standard output.
*/
private void log(String message) {
System.out.println(message);
}
}}
Client.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* Trivial client for the date server.
*/
public class Client {
private BufferedReader in;
private PrintWriter out;
private JFrame frame = new JFrame("Capitalize Client");
private JTextField dataField = new JTextField(40);
private JTextArea messageArea = new JTextArea(8, 60);
public Client() {
// Layout GUI
messageArea.setEditable(false);
frame.getContentPane().add(dataField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
// Add Listeners
dataField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(dataField.getText());
String response;
try {
response = in.readLine();
if (response == null || response.equals("")) {
System.exit(0);
}
} catch (IOException ex) {
response = "Error: " + ex;
}
messageArea.append(response + " ");
dataField.selectAll();
}
});
}
public void connectToServer() throws IOException {
// Get the server address from a dialog box.
String serverAddress = JOptionPane.showInputDialog(frame, "Enter IP Address of the Server:",
"Welcome to the Program", JOptionPane.QUESTION_MESSAGE);
// Make connection and initialize streams
Socket socket = new Socket(serverAddress, 9999);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Consume the initial welcoming messages from the server
for (int i = 0; i <1; i++) {
messageArea.append(in.readLine() + " ");
}
}
public static void main(String[] args) throws Exception {
Client client = new Client();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.pack();
client.frame.setVisible(true);
client.connectToServer();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.