Java This is a server & client based program. This program’s Server will start b
ID: 3863967 • 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.*;
import java.net.*;
public class Server{
public static void main(String args[]) throws IOException{
//Creating server socket on the port 1234
ServerSocket serverSocket = new ServerSocket(1234);
//Establishing the connection with client
Socket socket = serverSocket.accept();
//Initializing the stream for writing the ids
DataOutputStream dis = new DataOutputStream(socket.getOutputStream());
//Write the id to the client
dis.writeUTF("ID101");
dis.flush();
dis.close();
socket.close();
//For another client
socket= serverSocket.accept();
dis = new DataOutputStream(socket.getOutputStream());
dis.writeUTF("ID102");
dis.flush();
dis.close();
socket.close();
}
}
Client.java
import java.io.*;
import java.net.*;
class Client{
public static void main(String args[]) throws IOException{
//Opening the connection with the server on the port 1234
Socket socket=new Socket("localhost",1234);
//Opening the stream to read the data
DataInputStream dis = new DataInputStream(socket.getInputStream());
String id = (String)dis.readUTF();
System.out.println("ID is "+id);
socket.close();
}
}
OUPUT 1:
ID is ID101
OUTPUT 2:
ID is ID102
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.