Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming)
import java.io.*;
import java.net.*;
public class WelcomeClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port
number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket kkSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to "
+
hostName);
System.exit(1);
}
}
}
import java.net.*;
import java.io.*;
public class WelcomeServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java WelcomeServer <port
number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
// Initiate conversation with client
WelcomeProtocol wp = new WelcomeProtocol();
outputLine = wp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = wp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port
"
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
import java.net.*;
import java.io.*;
public class WelcomeProtocol {
private static final int WAITING = 0;
private static final int SENTWELCOME = 1;
private String str;
private int state = WAITING;
private int currentJoke = 0;
public String processInput(String theInput) {
String theOutput = null;
if (state == WAITING) {
theOutput = "Welcome!";
state = SENTWELCOME;
} else if (state == SENTWELCOME) {
if (theInput.equalsIgnoreCase("bye")) {
System.exit(1);
}
else {
str = theInput;
String str2 =
str.replaceAll("\\s","");
int length =
str2.length();
String len =
Integer.toString(length);
theOutput =
len;
state =
SENTWELCOME;
}
}
return theOutput;
}
}
Solution using java:
import java.io.*;
import java.util.*;
import java.net.*;
// Server class
public class Server
{
// Vector to store active clients
static Vector<ClientHandler> ar = new
Vector<>();
// counter for clients
static int i = 0;
public static void main(String[] args) throws
IOException
{
// server is listening on port
1234
ServerSocket ss = new
ServerSocket(1234);
Socket s;
// running infinite loop for
getting
// client request
while (true)
{
// Accept the
incoming request
s =
ss.accept();
System.out.println("New client request received : " + s);
// obtain input
and output streams
DataInputStream
dis = new DataInputStream(s.getInputStream());
DataOutputStream
dos = new DataOutputStream(s.getOutputStream());
System.out.println("Creating a new handler for this
client...");
// Create a
new handler object for handling this request.
ClientHandler
mtch = new ClientHandler(s,"client " + i, dis, dos);
// Create a
new Thread with this object.
Thread t = new
Thread(mtch);
System.out.println("Adding this client to active client list");
// add this
client to active clients list
ar.add(mtch);
// start the
thread.
t.start();
// increment
i for new client.
// i is used for
naming only, and can be replaced
// by any naming
scheme
i++;
}
}
}
// ClientHandler class
class ClientHandler implements Runnable
{
Scanner scn = new Scanner(System.in);
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
boolean isloggedin;
// constructor
public ClientHandler(Socket s, String name,
DataInputStream dis, DataOutputStream dos)
{
this.dis = dis;
this.dos = dos;
this.name = name;
this.s = s;
this.isloggedin=true;
}
@Override
public void run() {
String received;
while (true)
{
try
{
// receive the string
received = dis.readUTF();
System.out.println(received);
if(received.equals("logout")){
this.isloggedin=false;
this.s.close();
break;
}
// break the string into message and recipient
part
StringTokenizer st = new
StringTokenizer(received, "#");
String MsgToSend = st.nextToken();
String recipient = st.nextToken();
// search for the recipient in the connected
devices list.
// ar is the vector storing client of active
users
for (ClientHandler mc : Server.ar)
{
// if the recipient is found,
write on its
// output stream
if (mc.name.equals(recipient)
&& mc.isloggedin==true)
{
mc.dos.writeUTF(this.name+" : "+MsgToSend);
break;
}
}
} catch
(IOException e) {
e.printStackTrace();
}
}
try
{
// closing
resources
this.dis.close();
this.dos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming)...
I need help with my IM (instant messaging) java program, I created the Server, Client, and Message class. I somehow can't get both the server and client to message to each other. I am at a roadblock. Here is the question below. Create an IM (instant messaging) java program so that client and server communicate via serialized objects (e.g. of type Message). Each Message object encapsulates the name of the sender and the response typed by the sender. You may...
The DictionaryClient program featured in the class lecture also used the try-catch when creating a socket. Socket are auto-closeable and thus can use a try-with-resources instead. Edit the dictionary program to use try-with-resources instead. package MySockets; import java.net.*; import java.io.*; public class DictionaryClient { private static final String SERVER = "dict.org"; private static final int PORT = 2628; private static final int TIMEOUT = 15000; public static void main(String[] args) { Socket ...
How to solve this problem by using reverse String and Binary search? Read the input one line at a time and output the current line if and only if it is not a suffix of some previous line. For example, if the some line is "0xdeadbeef" and some subsequent line is "beef", then the subsequent line should not be output. import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet;...
Java only. Thanks These questions involve choosing the right abstraction (Collection, Set, List, Queue, Deque, SortedSet, Map, or SortedMap) to EFFICIENTLY accomplish the task at hand. The best way to do these is to read the question and then think about what type of Collection is best to use to solve it. There are only a few lines of code you need to write to solve each of them. Unless specified otherwise, sorted order refers to the natural sorted order...
Error: Main method not found in class ServiceProvider, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application This is the error im getting while executing the following code Can you modify the error import java.net.*; import java.io.*; public class ServiceProvider extends Thread { //initialize socket and input stream private Socket socket = null; private ServerSocket server = null; private DataInputStream in = null; private DataOutputStream out = null; private int...
In java write a simple 1-room chat server that is compatible with the given client code. 9 public class Client private static String addr; private static int port; private static String username; 14 private static iter> currenthriter new AtomicReference>(null); public static void main(String[] args) throws Exception [ addr -args[]; port Integer.parseInt (args[1]); username-args[21 Thread keyboardHandler new Thread(Main: handlekeyboardInput); 18 19 while (true) [ try (Socket socket -new Socket (addr, port) println(" CONNECTED!; Printwriter writer new Printwriter(socket.getoutputStreamO); writer.println(username); writer.flush); currenthriter.set(writer); BufferedReader...
Complete the Java command line application. The application accepts a URL from the command line. This application should then make a HTTP request to “GET” the HTML page for that URL, then print the HTTP header as well as the HTML for the page to the console. You must use the Java “socket” class to do all network I/O with the webserver. Yes, I’m aware this is on Stack Overflow, but you must understand how this works, as you will...
Please complete the give code (where it says "insert code here") in Java, efficiently. Read the entire input one line at a time and then output a subsequence of the lines that appear in the same order they do in the file and that are also in non-decreasing or non-increasing sorted order. If the file contains n lines, then the length of this subsequence should be at least sqrt(n). For example, if the input contains 9 lines with the numbers...
Please answer question correctly and show the result of the working code. The actual and demo code is provided .must take command line arguments of text files for ex : input.txt output.txt from a filetext(any kind of input for the text file should work as it is for testing the question) This assignment is about using the Java Collections Framework to accomplish some basic text-processing tasks. These questions involve choosing the right abstraction (Collection, Set, List, Queue, Deque, SortedSet, Map,...
Java Project Draw a class diagram for the below class (using UML notation) import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; public class myData { public static void main(String[] args) { String str; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter text (‘stop’ to quit)."); try (FileWriter fw = new FileWriter("test.txt")) { do { System.out.print(": "); str = br.readLine(); if (str.compareTo("stop") == 0) break; str = str + "\r\n"; // add newline fw.write(str); } while (str.compareTo("stop") != 0); } catch (IOException...