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...
Modify the socket-based date server below so that the server services each client request in a separate thread. import java.net.*; import java.io.*; public class DateClient { public static void main(String[] args) { try { /* make connection to server socket */ Socket sock = new Socket(“127.0.0.1”,6013); InputStream in = sock.getInputStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); /* read the date from the socket */ String line; while ( (line = bin.readLine()) != null) System.out.println(line); /* close the socket connection*/ sock.close(); ...
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 ...
please help. About java tcp. this is what i have so far. how to convert input value into ASCII sequence For example the message: “Hello World” would become “Ifmmp!Xpsme”For example the message: “Hello World” would become “Ifmmp!Xpsme”in server.java. Client.java: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.net.SocketTimeoutException; public class Client { public static void main(String[] args) throws IOException { Socket client = new Socket("127.0.0.1", 20006); client.setSoTimeout(10000); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintStream out...
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...
Running a program in Java about slidsender and slidreceiver with a brief explanation what each one is doing. slidreceiver import java.net.*; import java.io.*; class slidreceiver { public static void main(String a[])throws Exception { Socket s=new Socket(InetAddress.getLocalHost(),10); DataInputStream in=new DataInputStream(s.getInputStream()); PrintStream p=new PrintStream(s.getOutputStream()); int i=0,rptr=-1,nf,rws=8; String rbuf[]=new String[8]; String ch; System.out.println(); do { nf=Integer.parseInt(in.readLine()); if(nf<=rws-1) { for(i=1;i<=nf;i++) { rptr=++rptr%8; rbuf[rptr]=in.readLine(); System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]); } rws-=nf; System.out.println("\nAcknowledgment sent\n"); p.println(rptr+1); rws+=nf; } else break; ch=in.readLine(); } while(ch.equals("yes")); }...
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...