network.rar
In a screening I was asked to write a code for tcp connection supporting multiple clients. The code works, but my code was rejected bcoz it wasn't efficient.
Let me know, whats wrong.
thanks
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
network.rar
In a screening I was asked to write a code for tcp connection supporting multiple clients. The code works, but my code was rejected bcoz it wasn't efficient.
Let me know, whats wrong.
thanks
Rejected by who? Its always best to ask those that rejected for a reasonable explanation...further, I recommend you post the code directly here (use the code tags)...most folks including myself won't download whatever is in that link.
package com.test.network; /* The java.net package contains the basics needed for network operations. */ import java.net.*; import java.util.ResourceBundle; import java.io.*; import org.apache.log4j.Logger; public class SocketClient { private static final Logger logger = Logger.getLogger(SocketClient.class); private static ResourceBundle resources = ResourceBundle.getBundle("socket"); public static void main(String[] args) { String host = ""; String encoding = ""; int port; StringBuffer instr = new StringBuffer(); String fileID = "1000"; try { host=resources.getString("host"); port=new Integer(resources.getString("port")).intValue(); encoding=resources.getString("encoding"); logger.debug("file idnetifier:" + args[0]); /** Obtain an address object of the server */ InetAddress address = InetAddress.getByName(host); logger.debug("Inet Address" + address); /** Establish a socket connection */ Socket connection = new Socket(address, port); logger.debug("SocketClient initialized"); /** Instantiate a BufferedOutputStream object */ BufferedOutputStream bos = new BufferedOutputStream(connection. getOutputStream()); OutputStreamWriter osw = new OutputStreamWriter(bos, encoding); if (args[0] != null) fileID=args[0]; int fileIdentifier = new Integer(fileID).intValue(); String process = "JUNKJUNKJUKNKJUNKJUNK " ; logger.debug("file idnetifier:" + args[0]); /** Write across the socket connection and flush the buffer */ osw.write(process); osw.write("fID#" + fileIdentifier + (char) 13); osw.flush(); /** Instantiate a BufferedInputStream object for reading * incoming socket streams. */ BufferedInputStream bis = new BufferedInputStream(connection. getInputStream()); InputStreamReader isr = new InputStreamReader(bis); /**Read the socket's input and append to a StringBuffer */ int c; while ( (c = isr.read()) != 13) instr.append( (char) c); /** Close the socket connection. */ connection.close(); logger.debug(instr); } catch (IOException f) { logger.error("IOException: ", f); } catch (Exception g) { logger.error("Exception: ",g); } } }
package com.test.network; import java.net.*; import java.io.*; import java.util.*; import org.apache.log4j.Logger; public class SocketServer implements Runnable { protected static int port; Socket connection; static boolean first; static String filePath; private static final Logger logger = Logger.getLogger(SocketServer.class); private static ResourceBundle resources = ResourceBundle.getBundle("socket"); private int ID; private static int count = 0; SocketServer(Socket socket, int id) { this.connection = socket; this.ID = id; } public static void main(String[] args) { try { filePath = resources.getString("filePath"); port=new Integer(resources.getString("port")).intValue(); ServerSocket socket = new ServerSocket(port); System.out.println("SocketServer Initialized"); while (true) { Socket connection = socket.accept(); Runnable runnable = new SocketServer(connection, ++count); logger.debug("count:"+ count); Thread thread = new Thread(runnable); thread.start(); } } catch (Exception e) { System.out.println(e); } } public void run() { int character; String fileOutput = ""; StringBuffer process; String fileName; String originalFileName; try { BufferedInputStream is = new BufferedInputStream( connection.getInputStream()); InputStreamReader isr = new InputStreamReader(is); process = new StringBuffer(); while ((character = isr.read()) != 13) { process.append((char) character); } logger.debug("CLINET REQUEST RECEIVED" + process); // extract the file Name from the clients request String tempFileID = new String(process.toString()); int index = tempFileID.lastIndexOf("#"); String temp = tempFileID.substring(index + 1); originalFileName = temp; fileName = filePath + originalFileName + ".txt"; logger.debug("fileName:" + fileName); // 10 seconds delay in response Thread.sleep(10000); try { FileReader fr = new FileReader(new File(fileName)); BufferedReader br = new BufferedReader(fr); String s; while ((s = br.readLine()) != null) { fileOutput = fileOutput + s; } } catch (Exception e) { logger.error("File Reader ERROR:",e); throw e; } // write the filename request in count.txt file fileWriter(originalFileName); String returnCode = "The requested FileName : " + originalFileName + " And its associated Contents : \t" + fileOutput + (char) 13; BufferedOutputStream os = new BufferedOutputStream( connection.getOutputStream()); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(returnCode); osw.flush(); } catch (IOException e) { logger.error("IOEXception:",e); } catch (Exception e) { logger.error("Xception:",e); } finally { try { connection.close(); } catch (IOException e) { } } } static void fileWriter(String str) { try { String TimeStamp; File fileOutput = new File(filePath + "count.txt"); FileWriter fstream = new FileWriter(fileOutput, true); BufferedWriter out = new BufferedWriter(fstream); TimeStamp = new java.util.Date().toString(); out.newLine(); out.write(TimeStamp + ":" + str); out.close(); } catch (Exception e) { System.out.println(" Error while writing the requested filename" + e); } } }
I know this is an old Thread and I apologize, however, the unanswered question interests me greatly.
The TL;DR version of the OPs code is MultiThreading with Sockets. Ie, creating a new Thread for every new connection - I've searched the web for an alternative effective way of handling multiple clients and ultimately ended up here and all I've got is the same old multithreading solution.
Can anyone share insight on what is the new, standard, correct way of handling multiple clients?
Thank you.
It could be that what you're looking for is non-blocking IO with Channels in Java NIO:Can anyone share insight on what is the new, standard, correct way of handling multiple clients?
JDK 1.4.2 New I/O-related APIs & Developer Guides -- from Sun Microsystems
mobydickus (April 9th, 2012)
I think you're right. I came across this Java.NIO very recently while searching for the solution and found this article helpful for understanding the main differences (advantages) between IO and NIO as well as giving a sneak peek into NIO:
Java NIO vs. IO | Javalobby
Java NIO: Introduction
Rox Java NIO Tutorial
Last edited by mobydickus; April 9th, 2012 at 05:03 PM. Reason: More useful Links
Also those looking for a NIO library: kryonet - TCP and UDP client/server library for Java - Google Project Hosting
For completeness sake. I read the above links and also read the book called Java.NIO (which was only about a century of pages) and made a Java NIO Echo server implementation.
Here's an abstract class template for a Server that I made. I hope it gives some insight on how you're supposed to do it with NIO.
import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.util.Iterator; /** * Java NIO template Server. * @author Ada * */ public abstract class ChanServer implements Runnable { public final String NAME; public final int PORT; private final ServerSocketChannel ssc; private final ServerSocket ss; private final Selector selector; private boolean running = false; private boolean paused = false; private final Thread thread; public ChanServer(int port, String name) throws IOException { this.PORT = port; this.NAME = name; System.out.println(NAME + " initializing."); ssc = ServerSocketChannel.open(); ss = ssc.socket(); selector = Selector.open(); ss.bind(new InetSocketAddress(this.PORT)); ssc.configureBlocking(false); // Important! The core idea behind NIO ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println(NAME + " listening on PORT " + PORT); running = true; thread = new Thread(this); thread.start(); } @Override public void run() { while (running) { int updatedKeysCount; try { updatedKeysCount = selector.select(); // Blocking if (updatedKeysCount <= 0) { // Nothing to update continue; } // Iterator over the selected (updated) keys Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); if (key.isAcceptable()) { accept(key.channel()); } if (key.isReadable()) { read(key.channel()); } // Remove key from Selected list it.remove(); } } catch (IOException ioe) { ioe.printStackTrace(); } } System.out.println(NAME + " closing."); } /** * A new Connection has been Accepted. * Write your own implementation. * @param selectableChannel */ protected void accept(SelectableChannel selectableChannel) { } /** * New data is available for reading. * Write your own implementation. * @param selectableChannel */ protected void read(SelectableChannel selectableChannel) { } /** * Closes the Channel. * @param selectableChannel * @throws IOException */ protected void close(SelectableChannel selectableChannel) throws IOException { selectableChannel.close(); } protected void start() { if (!running) { running = true; thread.start(); return; } thread.notify(); paused = false; System.out.println(NAME + " resumed."); } protected void pause() { paused = true; try { thread.interrupt(); System.out.println(NAME + " paused."); thread.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } protected void stop() { running = false; thread.interrupt(); } }
Last edited by mobydickus; April 30th, 2012 at 01:48 AM.