Skip to content

Instantly share code, notes, and snippets.

@akhld
Created December 12, 2014 13:12
Show Gist options
  • Save akhld/4286df9ab0677a555087 to your computer and use it in GitHub Desktop.
Save akhld/4286df9ab0677a555087 to your computer and use it in GitHub Desktop.
JavaServerSocket, listens to a port and sends the content of the given file
package com.sigmoidanlytics;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
public class SocketBenchmark {
public static void main(String[] args) {
if(args.length != 3){
System.out.println("Usage:\njava -jar benchmark.jar <input-text-file> <port> <io/nio>");
System.exit(0);
}
try{
if(args[2].equalsIgnoreCase("io")){
System.out.println("Server IO initiating...");
ServerSocket server = new ServerSocket(Integer.parseInt(args[1]));
int i = 1;
while(i != 0 ){
Socket sock = server.accept();
System.out.println("Server connected to client successfully");
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
System.out.println("Server initiating transfer - Timer starting");
long start = System.currentTimeMillis();
BufferedReader br = new BufferedReader(new FileReader(args[0]));
String line = "";
while ((line = br.readLine()) != null) {
// System.out.println(line);
out.write(line + "\n");
out.flush();
}
out.flush();
sock.close();
long end = System.currentTimeMillis();
System.out.println("Network IO transfer " + (Paths.get(args[0]).toFile().length()/1048576) + " mb in "+(end-start)+" ms");
}
server.close();
}else if(args[2].equalsIgnoreCase("nio")){
System.out.println("Server NIO initiating...");
ServerSocketChannel serverChan = ServerSocketChannel.open();
serverChan.bind(new InetSocketAddress(Integer.parseInt(args[1])));
int i = 1;
while(i != 0 ){
SocketChannel chan = serverChan.accept();
chan.configureBlocking(false);
System.out.println("Server channel connected");
System.out.println("Server initiating transfer - Timer starting");
Long start = System.currentTimeMillis();
BufferedReader br = new BufferedReader(new FileReader(args[0]));
String line = "";
while ((line = br.readLine()) != null) {
// System.out.println(line);
chan.write(ByteBuffer.wrap((line + "\n").getBytes()));
}
chan.close();
Long end = System.currentTimeMillis();
System.out.println("Network IO transfer " + (Paths.get(args[0]).toFile().length()/1048576) + " mb in "+(end-start)+" ms");
}
serverChan.close();
}
}catch(Exception e){
System.out.println("Whoops!! => " + e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment