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 socket =
null;
try {
socket = new
Socket(SERVER, PORT);
socket.setSoTimeout(TIMEOUT);
System.out.print("Connected to Host : ");
System.out.print(socket.getInetAddress() + " Port: ");
System.out.println(socket.getPort());
System.out.print("Connected from Host:" );
System.out.print(socket.getLocalAddress() + " Port: ");
System.out.println(socket.getLocalPort());
InputStream in =
socket.getInputStream();
BufferedReader
reader = new BufferedReader(new InputStreamReader(in,
"UTF-8"));
OutputStream out
= socket.getOutputStream();
Writer writer =
new OutputStreamWriter(out, "UTF-8");
writer = new
BufferedWriter(writer);
define(args[0],
writer, reader);
} catch (IOException ex) {
System.err.println(ex);
} finally {
if(socket !=
null) {
try {
socket.close();
} catch(IOException e) {
System.out.println(e);
}
}
}
}
static void define(String word,
Writer writer,
BufferedReader reader) throws
IOException {
writer.write("SHOW DB\r\n");
writer.write("DEFINE fd-eng-lat " +
word + "\r\n");
writer.flush();
for(String line =
reader.readLine(); line != null; line = reader.readLine()) {
System.out.println(line);
if(line.startsWith("250 ")) {
writer.write("quit\r\n");
writer.flush();
}
}
return;
}
}
Please find the answer below:
I have highlighted the changed part of the program.
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) {
//no need of this line as we will use the tr with resource
//Socket socket = null;
//object is created using tr with resources and it implements the auto closeable so no need of the finally method
try(Socket socket = new Socket(SERVER, PORT)) {
socket.setSoTimeout(TIMEOUT);
System.out.print("Connected to Host : ");
System.out.print(socket.getInetAddress() + " Port: ");
System.out.println(socket.getPort());
System.out.print("Connected from Host:" );
System.out.print(socket.getLocalAddress() + " Port: ");
System.out.println(socket.getLocalPort());
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
OutputStream out = socket.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer = new BufferedWriter(writer);
define(args[0], writer, reader);
} catch (IOException ex) {
System.err.println(ex);
}
//fnally block is not required to close the socket
/*
finally{
if(socket != null) {
try {
socket.close();
} catch(IOException e) {
System.out.println(e);
}
}
}
*/
}
static void define(String word,
Writer writer,
BufferedReader reader) throws IOException {
writer.write("SHOW DB\r\n");
writer.write("DEFINE fd-eng-lat " + word + "\r\n");
writer.flush();
for(String line = reader.readLine(); line != null; line = reader.readLine()) {
System.out.println(line);
if(line.startsWith("250 ")) {
writer.write("quit\r\n");
writer.flush();
}
}
return;
}
}
/** * Please find the updated solution with try with resources * I have bolded the required part and removed finally block */
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) {
try (Socket socket = new Socket(SERVER, PORT)) {
socket.setSoTimeout(TIMEOUT);
System.out.print("Connected to Host : ");
System.out.print(socket.getInetAddress() + " Port: ");
System.out.println(socket.getPort());
System.out.print("Connected from Host:");
System.out.print(socket.getLocalAddress() + " Port: ");
System.out.println(socket.getLocalPort());
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
OutputStream out = socket.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer = new BufferedWriter(writer);
define(args[0], writer, reader);
} catch (IOException ex) {
System.err.println(ex);
}
// Removed finally block from here, it will be handled by we use try with resources
}
static void define(String word,
Writer writer,
BufferedReader reader) throws IOException {
writer.write("SHOW DB\r\n");
writer.write("DEFINE fd-eng-lat " + word + "\r\n");
writer.flush();
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
System.out.println(line);
if (line.startsWith("250 ")) {
writer.write("quit\r\n");
writer.flush();
}
}
return;
}
}
The DictionaryClient program featured in the class lecture also used the try-catch when creating a socket....
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...
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...
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(); ...
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...
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...
I need help with adding comments to my code and I need a uml diagram for it. PLs help.... Zipcodeproject.java package zipcodesproject; import java.util.Scanner; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Zipcodesproject { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input=new Scanner(System.in); BufferedReader reader; int code; String state,town; ziplist listOFCodes=new ziplist(); try { reader = new BufferedReader(new FileReader("C:UsersJayDesktopzipcodes.txt")); String line = reader.readLine(); while (line != null) { code=Integer.parseInt(line); line =...
import java.io.*; import java.util.Scanner; public class CrimeStats { private static final String INPUT_FILE = "seattle-crime-stats-by-1990-census-tract-1996-2007.csv"; private static final String OUTPUT_FILE = "crimes.txt"; public static void main(String[] args) { int totalCrimes = 0; // read all the rows from the csv file and add the total count in the totalCrimes variable try { Scanner fileScanner = new Scanner(new File(INPUT_FILE)); String line = fileScanner.nextLine(); // skip first line while (fileScanner.hasNext()) { String[] tokens = fileScanner.nextLine().split(","); if (tokens.length == 4) { totalCrimes +=...
Please help me fix my errors. I would like to read and write the text file in java. my function part do not have errors. below is my code import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.IOException; public class LinkedList { Node head; class Node { int data; Node next; Node(int d) { data = d; next = null; } } void printMiddle() { Node slow_ptr...
COMPILER ERROR PLS HELP CAPITALIZE FIRST LETTER OF EACH WORD IN STRING IN JAVA public class Main { /** * Iterate through each line of input. */ public static void main(String[] args) throws IOException { InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8); BufferedReader in = new BufferedReader(reader); String line; while ((line = in.readLine()) != null) { line = Character.toUpperCase(line.charAt(0)) + line.subtring(1) + (" "); System.out.println(line); } } }
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...