Java String Index Out of Range in Proxy - java

Hey Guys my following code is a proxy written in java.
Everytime I try to run it, it throws an String Index out of range:-1 exception, which I don't know how to handle.
I also nee to redirect the request to a specific webpage, if a "bad" word has been written in the URL or the content of the web page.
How do I do that?
Please Help me!
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ProxyServer{
//Create the Port the user wants the proxy to be on
static Scanner sc = new Scanner(System.in);
public static final int portNumber = sc.nextInt();
public static void main(String[] args) {
ProxyServer proxyServer = new ProxyServer();
proxyServer.start();
}
public void start() {
System.out.println("Starting the SimpleProxyServer ...");
try {
//bad list of words
String bad[]= new String[4];
bad[0]= "SpongeBob";
bad[1]= "Britney Spears";
bad[2]= "Norrköping";
bad[3]= "Paris Hilton";
ServerSocket serverSocket = new ServerSocket(ProxyServer.portNumber);// this is the socket of the proxy
System.out.println(serverSocket);
byte[] buffer= new byte [10000] ;
//
while (true) {
Socket clientSocket = serverSocket.accept(); // the client willl be the socket the proxy "accepts"
boolean badContent =false; //flag, if the input contains one of the bad words
InputStream inputstream = clientSocket.getInputStream(); // retreiving request from the client
int n = inputstream.read(buffer); //reading buffer and storing its size
String browserRequest= new String(buffer,0,n+1); //new String(buffer,0,n);
String realbrowserRequest =( browserRequest+"Connection close()");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
for (int j=0; j<bad.length;j++){ //checking of the URL contains the bad words
if(realbrowserRequest.contains(bad[j])){
badContent =true; // if yes the flag will be set to true
}
}
//if(badContent == true){
//System.out.println("bad detected");
// try
// {
// URL url = new URL( "http://www.ida.liu.se/~TDTS04/labs/2011/ass2/error2.html" );
//
// BufferedReader in = new BufferedReader(
// new InputStreamReader( url.openStream() ) );
//
// String s;
//
// while ( ( s = in.readLine() ) != null )
// System.out.println( s );
//
// in.close();
// }
// catch ( MalformedURLException e ) {
// System.out.println( "MalformedURLException: " + e );
// }
// catch ( IOException e ) {
// System.out.println( "IOException: " + e );
// }
// else{
System.out.println("Das ist der Browserrequest: \n"+realbrowserRequest);
System.out.println("Das ist der Erste Abschnitt");
int start = browserRequest.indexOf(("Host: ") + 6);
int end = browserRequest.indexOf('\n', start);
String host = browserRequest.substring(start, end-1 ); //retreiving host
if(badContent =true) //if the URL already contains inappropriate material
{
URL url = new URL( "http://www.ida.liu.se/~TDTS04/labs/2011/ass2/error2.html" );
host = url.getHost(); // set the host to the given one
}
System.out.println("Connecting to host " + host);
Socket hostSocket = new Socket(host, 80); //I can change the host over here
OutputStream HostOutputStream = hostSocket.getOutputStream();
// PrintWriter writer= new PrintWriter (HostOutputStream);
// writer.println();
System.out.println("Forwarding request to server");
HostOutputStream.write(buffer, 0, n);// but then the buffer that is fetched from the client remains same
HostOutputStream.flush();
InputStream HostInputstream = hostSocket.getInputStream();
OutputStream ClientGetOutput = clientSocket.getOutputStream();
System.out.println("Forwarding request from server");
do {
n = HostInputstream.read(buffer);
String vomHost = new String(buffer,0,n);
System.out.println("\nVom Host\n\n"+vomHost);
for(int i=0;i<bad.length;i++){
if(vomHost.contains(bad[i])){
badContent=true;
}
}
System.out.println("Receiving " + n + " bytes");
if (n > 0) { // && badContent == false
ClientGetOutput.write(buffer, 0, n);
}
} while (n>0 && badContent == false); //n>0&& badContent == false
if (badContent == true){
}
ClientGetOutput.flush();
hostSocket.close();
clientSocket.close();
System.out.println("End of communication");
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}

The issue is here :
int start = browserRequest.indexOf(("Host: ") + 6);
This means you are doing this :
int start = browserRequest.indexOf("Host: 6");
6 is being concatenated to "Host : "
Try this :
int start = browserRequest.indexOf("Host: ") + 6;

There are many issues in your code:
1) Change the line :
int start = browserRequest.indexOf(("Host: ") + 6);
To:
int start = browserRequest.indexOf("Host:") + 6;
As mentioned in ToYonos's answer, becuase it is wrong.
2) You have to make sure that the two variables start and end are not equal to -1(if they doesn't exist in browserRequest):
if(end>start && start>0)
{
String host = browserRequest.substring(start, end-1 );
}
This will avoid many Exceptions.

Related

Java Sockets - Sending an object from the server and receiving/displaying it to the client

I am trying to send an object from my server and then receiving it/displaying it on the client side. The object in question has a few parameters tied to it, such as int values and string values. Do I also need to have a version of my server class on the client side in which to store the values from the input stream?
I have tried the following:
Server
public void run() {
int height = 6;
int width = 9;
int moves = height * width;
System.out.println("Connected: " + socket);
try {
Server server = new Server(val1, val2, str1, str2);
Scanner scanner = new Scanner(socket.getInputStream());
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
// while (scanner.hasNextInt()) {
// printWriter.println(scanner.nextInt());
// }
System.out.println(server );
// printWriter.println(server );
serverOutputStream.writeObject(server );
// while (scanner.hasNextInt()) {
for (int player = 0; moves-- > 0; player = 1 - player) {
char symbol = PLAYERS[player];
server.doSomething(symbol, scanner);
// printWriter.println(scanner.nextInt());
System.out.println(server);
// printWriter.println(server);
serverOutputStream.writeObject(server);
if (server.hasWon()) {
System.out.println("\nPlayer " + symbol + " wins!");
return;
}
// }
}
} catch (Exception exception) {
System.out.println("Error: " + socket);
} finally {
try {
socket.close();
} catch (IOException e) {
}
System.out.println("Closed: " + socket);
}
}
Client
public static void main(String[] args) throws Exception {
// if (args.length != 1) {
// System.err.println("Pass the server IP as the sole command line argument");
//
// return;
// }
try (Socket socket = new Socket("127.0.0.1", 59898)) {
System.out.println("Enter a move: ");
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
Object object = serverInputStream.readObject();
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
serverOutputStream.writeObject(object);
}
}
}

Newbie getting nullPointers all over the place [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
So I'm trying to create an smtp from scratch, (assignment) and I'm trying to connect classes together but miserably failing and trying everything out. The compiler doesn't throw up any errors but when I run it I don't get very far. I tried calling the other classes with the .start thread but still, failure
If you could help me or give tips, I would really appreciate it
//Problem seems to be here: I have no idea how to correct it
socketManager soketManager = null;
DataInputStream clientDataIn = new DataInputStream(soketManager.getInputStream());
socketManager clientReaderSocket = soketManager;```
public class socketManager {
public Socket soc = null;`
`
//socketManager.java
public DataInputStream input = null;
public DataOutputStream output = null;
public socketManager(Socket socket) throws IOException {
soc = socket;
input = new DataInputStream(soc.getInputStream());
output = new DataOutputStream(soc.getOutputStream());
}
public InputStream getInputStream() throws IOException {
input = new DataInputStream(soc.getInputStream());
return null;
}
public OutputStream getOutputStream() throws IOException {
output = new DataOutputStream(soc.getOutputStream());
return null;
}
}
Exception in thread "Thread-1" java.lang.NullPointerException at
me.censored.loopback.SMTPclient.Client$ClientSocketManager.run(Client.java:117)
at java.base/java.lang.Thread.run(Thread.java:834)
// Main Method:- called when running the class file.
public static void main(String[] args) throws UnknownHostException, IOException {
Port Declaration & Checks.
String serverIP = "loopback";
int defaultServerPort = 25;
PortManager portManage = new PortManager();
Thread portManagerThread = new Thread(portManage);
portManagerThread.start();
}// End of main
static public class PortManager implements Runnable {
Scanner userInput = new Scanner(System.in);
int serverPort = 25;
// Will accept only tcp/udp ports as of (2019) After several attempts the port
// will be auto selected to default 25,
// Should we accept parsed HEX?
boolean portCompletion = false;
short portTriesCounter = 1;
public void run() {
try {
do {
// Asks user for server's port at the start up of the client.
System.out.println("Please enter the port the server is on.");
String userEntry = userInput.nextLine();
userInput.close();
try {
serverPort = Integer.parseInt(userEntry);
if (portTriesCounter != 5) { // Partial tries timeout.
if (serverPort != 0) { // "Port Zero" does not officially exist. It is defined as an invalid
// port
// number. But valid Internet packets can be formed and sent "over
// the
// wire"
// to and from "port 0" just as with any other ports.
if ((serverPort > 0 && serverPort <= 1023)
|| (serverPort >= 1024 && serverPort <= 49151)
|| (serverPort >= 49152 && serverPort <= 65535)) // Check for ports inside the
// tcp/udp
// range
portCompletion = true;
else {
System.out.println(
"Wrong input! Make sure you are using correct numbers and port range! ");
portCompletion = false;
portTriesCounter++;
}
// End Check for ports inside the tcp/udp range
} else {
System.out.print("Wrong input! ");
portCompletion = false;
portTriesCounter++;
}
// End Check for zero
}
// End Too many attempts
else {
portTriesCounter = 5;
portCompletion = true;
System.out.print("Many wrong attemps. Selecting and trying the default port (25)... ");
try {
System.out.print("Success");
portCompletion = true;
serverPort = 25; // For SSL connections use port 465.
} catch (Exception except) {
portCompletion = false;
}
}
} catch (Exception except) {
portCompletion = false;
portTriesCounter++;
} finally {
userInput.close();
}
} while (!portCompletion);
ClientSocketManager clientSocketManage = new ClientSocketManager();
Thread clientSocketManagerThread = new Thread(clientSocketManage);
clientSocketManagerThread.start();
System.out.println("DEBUG 0");
} catch (Exception except) { // Any Failure will send 421 Error to client
System.out.println("\t 421 \t Service not available, closing transmission channel.\n" + except);
}
}
}
static class ClientSocketManager implements Runnable {
public void run() {
try {
String CRLF = "\r\n";
String LF = "\n";
boolean SocketInitiation = false;
socketManager soketManager = null;
DataInputStream clientDataIn = new DataInputStream(soketManager.getInputStream());
socketManager clientReaderSocket = soketManager;
DataOutputStream clientDataOut;
clientDataOut = new DataOutputStream(soketManager.getOutputStream());
String sendSocketMessage = (CRLF);
clientDataOut.writeUTF(sendSocketMessage);// Sends string to output stream using UTF-8
clientDataOut.flush();
System.out.println("DEBUG 1");
String socketReplyIn = clientDataIn.readUTF();
PortManager portInstance = new PortManager();
int portNumber = portInstance.serverPort;
Socket soket = new Socket("loopback", portNumber);
ClientWriter clientWrite = new ClientWriter(soket);
Thread clientWriteThread = new Thread(clientWrite);
ClientReader clientRead = new ClientReader(soket);
Thread clientReadThread = new Thread(clientRead);
System.out.println("DEBUG 2");
// Cleans stream from any write buffer method.
System.out.println("Connection to server using TCP...");
if (socketReplyIn.contains("220")) {
System.out.println("\t 220 \t Service ready"); // Connection established successfully
clientReadThread.start();
clientWriteThread.start();
SocketInitiation = true;
} else {
System.out.println("\t 421 \t Service not available, closing transmission channel");
SocketInitiation = false;
}
} catch (IOException e) {
System.out.println("\t 421 \t Service not available, closing transmission channel");
System.out.println("TCP connection error: " + e);
}
}
}
you have defined socketManager soketManager = null; in ClientSocketManager.
but you never assigned a value to it, so it is still null.
The code after that is trying to access streams from it, which is throwing NullPointerException:
DataInputStream clientDataIn = new DataInputStream(soketManager.getInputStream());
socketManager clientReaderSocket = soketManager;
DataOutputStream clientDataOut;
clientDataOut = new DataOutputStream(soketManager.getOutputStream());
String sendSocketMessage = (CRLF);
clientDataOut.writeUTF(sendSocketMessage);// Sends string to output stream using UTF-8
clientDataOut.flush();
System.out.println("DEBUG 1");
just create a new instance of the socketManager and assign it to soketManager before using it.
PortManager portInstance = new PortManager();
int portNumber = portInstance.serverPort;
Socket soket = new Socket("loopback", portNumber);
socketManager soketManager = new sockerManager(soket);

What is the problem of this code...? Java socket programming

I am coding client-server multithread calculator using java, socket programming.
There's any syntax error, but msgs cannot be received from server.
I think
receiveString = inFromServer.readLine()
does not works. This code is in Client program, in the while(true) loop.
What is the problem?
Here is my full code.
SERVER
import java.io.*;
import java.net.*;
public class Server implements Runnable
{
static int max = 5; //maximum thread's number
static int i = 0, count = 0; //i for for-loop, count for count number of threads
public static void main(String args[]) throws IOException
{
ServerSocket serverSocket = new ServerSocket(6789); //open new socket
File file = new File("src/serverinfo.dat"); //make data file to save server info.
System.out.println("Maximum 5 users can be supported.\nWaiting...");
for(i=0; i <= max; i++) { new Connection(serverSocket); } //make sockets - loop for max(=5) times
try //server information file writing
{
String dataString = "Max thread = 5\nServer IP = 127.0.0.1\nServer socket = 6789\n";
#SuppressWarnings("resource")
FileWriter dataFile = new FileWriter(file);
dataFile.write(dataString);
}
catch(FileNotFoundException e) { e.printStackTrace(); }
catch(IOException e) { e.printStackTrace(); }
}
static class Connection extends Thread
{
private ServerSocket serverSocket;
public Connection(ServerSocket serverSock)
{
this.serverSocket = serverSock;
start();
}
public void run()
{
Socket acceptSocket = null;
BufferedReader inFromClient = null;
DataOutputStream msgToClient = null;
String receiveString = null;
String result = "", sys_msg = "";
try
{
while(true)
{
acceptSocket = serverSocket.accept(); // 접속수락 소켓
count++;
inFromClient = new BufferedReader(new InputStreamReader(acceptSocket.getInputStream()));
msgToClient = new DataOutputStream(acceptSocket.getOutputStream());
System.out.println(count + "th client connected: " + acceptSocket.getInetAddress().getHostName() + " " + count + "/" + max);
System.out.println("Waiting response...");
while(true)
{
if (count >= max+1) // if 6th client tries to access
{
System.out.println("Server is too busy. " + max + " clients are already connected. Client access denied.");
sys_msg = "DENIED";
msgToClient.writeBytes(sys_msg);
acceptSocket.close();
count--;
break;
}
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
try{ receiveString = inFromClient.readLine(); }
catch(Exception e) // if receiveString = null
{
System.out.println("Connection Close");
count--;
break;
}
System.out.println("Input from client : " + receiveString);
try
{
if(receiveString.indexOf("+") != -1) { result = cal("+", receiveString); }
else if(receiveString.indexOf("-") != -1) { result = cal("-", receiveString); }
else if(receiveString.indexOf("/") != -1) { result = cal("/", receiveString); }
else if(receiveString.indexOf("*") != -1) { result = cal("*", receiveString); }
else if(receiveString.indexOf("+") == -1 || receiveString.indexOf("-") == -1 || receiveString.indexOf("*") == -1 || receiveString.indexOf("/") == -1) { result = "No INPUT or Invalid operation"; }
}
catch(Exception e){ result = "Wrong INPUT"; }
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
}
}
}
catch(IOException e) { e.printStackTrace(); }
}
}
private static String cal(String op, String recv) //function for calculating
{
double digit1, digit2; //first number, second number
String result = null;
digit1 = Integer.parseInt(recv.substring(0, recv.indexOf(op)).trim());
digit2 = Integer.parseInt(recv.substring(recv.indexOf(op)+1, recv.length()).trim());
if(op.equals("+")) { result = digit1 + " + " + digit2 + " = " + (digit1 + digit2); }
else if(op.equals("-")) { result = digit1 + " - " + digit2 + " = " + (digit1 - digit2); }
else if(op.equals("*")) { result = digit1 + " * " + digit2 + " = " + (digit1 * digit2); }
else if(op.equals("/"))
{
if(digit2 == 0){ result = "ERROR OCCURRED: Cannot be divided by ZERO"; }
else{ result = digit1 + " / " + digit2 + " = " + (digit1 / digit2); }
}
return result;
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
-----------------------------------------------------------------
CLIENT
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws IOException
{
Socket clientSocket = null;
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromServer = null;
DataOutputStream msgToServer = null;
String sendString = "", receiveString = "";
try
{
clientSocket = new Socket("127.0.0.1", 6789); //make new clientSocket
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
msgToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Input exit to terminate");
System.out.println("Connection Success... Waiting for permission");
while(true)
{
receiveString = inFromServer.readLine();
if(receiveString.equals("DENIED"))
{
System.out.println("Server is full. Try again later.");
break;
}
else { System.out.println("Connection permitted."); }
System.out.print("Input an expression to calculate(ex. 3+1): ");
sendString = userInput.readLine();
if(sendString.equalsIgnoreCase("exit")) //when user input is "exit" -> terminate
{
clientSocket.close();
System.out.println("Program terminated.");
break;
}
try { msgToServer.writeBytes(sendString); }
catch(Exception e) {}
try { receiveString = userInput.readLine(); }
catch(Exception e) {}
System.out.println("Result: " + receiveString); //print result
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You've set up your server socket stack wrong.
Your code will make 5 threads, each calling accept on a serversocket.
The idea is to have a single ServerSocket (and not 5, as in your example). Then, this single serversocket (running in a single thread that handles incoming sockets flowing out of this serversocket) will call .accept which will block (freeze the thread) until a connection is made, and will then return a Socket object. You'd then spin off a thread to handle the socket object, and go right back to the accept call. If you want to 'pool' (which is not a bad idea), then disassociate the notion of 'handles connections' from 'extends Thread'. For example, implement Runnable instead. Then pre-create the entire pool (for example, 10 threads), have some code that lets you 'grab a thread' from the pool and 'return a thread' to the pool, and now the serversocket thread will, upon accept returning a socket object, grab a thread from the pool (which will block, thus also blocking any incoming clients, if every thread in the pool is already taken out and busy handling a connection), until a thread returns to the pool. Alternatively, the serversocket code checks if the pool is completely drained and if so, will put on a final thread the job of responding to that client 'no can do, we are full right now'.
I'm not sure if you actually want that; just.. make 1 thread per incoming socket is a lot simpler. I wouldn't dive into pool concepts until you really need them, and if you do, I'd look for libraries that help manage them. I think further advice on that goes beyond the scope of this question, so I'll leave the first paragraph as an outlay of how ServerSocket code ought to work, for context.

Filtering URL content in a self written proxy using Java

I need to code some proxy server for an assignment in my university. It should be able to display the content of some simple web page given by our professor.
Additionally it should filter the URL and the URL content, and block the web page if one of these contain one of the words in my "bad" array.
My question is, how can I perform this filtering in Java.
Code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ProxyServer{
//Crate the Port the user wants the proxy to be on
static Scanner sc = new Scanner(System.in);
public static final int portNumber = sc.nextInt();
public static void main(String[] args) {
ProxyServer proxyServer = new ProxyServer();
proxyServer.start();
}
public void start() {
System.out.println("Starting the SimpleProxyServer ...");
try {
String bad[]= new String[4];
bad[0]= "Spongebob";
bad[1]= "Britney Spears";
bad[2]= "Norrköping";
bad[3]= "Paris Hilton";
ServerSocket serverSocket = new ServerSocket(ProxyServer.portNumber);
System.out.println(serverSocket);
byte[] buffer= new byte [1000000] ;
while (true) {
Socket clientSocket = serverSocket.accept();
InputStream inputstream = clientSocket.getInputStream();
System.out.println(" DAS PASSIERT VOR DEM BROWSER REQUEST:");
int n = inputstream.read(buffer);
String browserRequest = new String(buffer,0,n);
System.out.println("Das ist der Browserrequest: "+browserRequest);
System.out.println("Das ist der Erste Abschnitt");
int start = browserRequest.indexOf("Host: ") + 6;
int end = browserRequest.indexOf('\n', start);
String host = browserRequest.substring(start, end - 1);
System.out.println("Connecting to host " + host);
Socket hostSocket = new Socket(host, 80); //I can change the host over here
OutputStream HostOutputStream = hostSocket.getOutputStream();
PrintWriter writer= new PrintWriter (HostOutputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
String Input= null;
while (((Input= reader.readLine())!= null)){
writer.write(Input);
writer.flush();
System.out.println("Empfangen vom Client: "+Input);
}
// for (int i=0; i<4;i++){
// if (inString.contains(bad[i])){
// System.out.println("Bye Idiot");
// break;
// }
// }
System.out.println("Forwarding request to server");
HostOutputStream.write(buffer, 0, n);// but then the buffer that is fetched from the client remains same
HostOutputStream.flush();
InputStream HostInputstream = hostSocket.getInputStream();
OutputStream ClientGetOutput = clientSocket.getOutputStream();
System.out.println("Forwarding request from server");
do {
n = HostInputstream.read(buffer);
String inhalt= HostInputstream.toString();
System.out.println("das ist der inhalt vom HOST: "+ inhalt);
String vomHost = new String(buffer,0,n);
System.out.println("Vom Host\n\n"+vomHost);
// for(int i=0;i<n;i++){
// System.out.print(buffer[i]);
// }
System.out.println("Receiving " + n + " bytes");
if (n > 0) {
ClientGetOutput.write(buffer, 0, n);
}
} while (HostInputstream.read(buffer)!= -1);//n>0
ClientGetOutput.flush();
hostSocket.close();
clientSocket.close();
System.out.println("End of communication");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Message returned is null

Hi i have a problem with my server, everytime i call "dload" the file gets downloaded but i can't use the other commands i have because they get returned as null. Anyone who can see the problem in the code?
Server :
public class TCPServer {
public static void main(String[] args) {
ServerSocket server = null;
Socket client;
// Default port number we are going to use
int portnumber = 1234;
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
// Create Server side socket
try {
server = new ServerSocket(portnumber);
} catch (IOException ie) {
System.out.println("Cannot open socket." + ie);
System.exit(1);
}
System.out.println("ServerSocket is created " + server);
// Wait for the data from the client and reply
boolean isConnected = true;
try {
// Listens for a connection to be made to
// this socket and accepts it. The method blocks until
// a connection is made
System.out.println("Waiting for connect request...");
client = server.accept();
System.out.println("Connect request is accepted...");
String clientHost = client.getInetAddress().getHostAddress();
int clientPort = client.getPort();
System.out.println("Client host = " + clientHost
+ " Client port = " + clientPort);
// Read data from the client
while (isConnected == true) {
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
String msgFromClient = br.readLine();
System.out.println("Message received from client = "
+ msgFromClient);
// Send response to the client
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("sum")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Double sum = 0.0;
for (int k = 0; k < 5; k++) {
sum = sum + list[k];
}
pw.println("Sum of array is " + sum);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("max")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Double[] list;
list = new Double[5];
String value;
int i;
try {
for (i = 0; i < 5; i++) {
pw.println("Input number in arrayslot: " + i);
value = br.readLine();
double DoubleValue = Double.parseDouble(value);
list[i] = DoubleValue;
}
if (i == 5) {
Arrays.sort(list);
pw.println("Max integer in array is " + list[4]);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("time")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Time is:, "
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE);
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("date")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
Calendar calendar = GregorianCalendar.getInstance();
String ansMsg = "Date is: " + calendar.get(Calendar.DATE)
+ "/" + calendar.get(Calendar.MONTH) + "/"
+ calendar.get(Calendar.YEAR);
;
pw.println(ansMsg);
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("c2f")) {
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
String celciusValue;
boolean ifRead = false;
try {
pw.println("Input celcius value");
celciusValue = br.readLine();
ifRead = true;
if (ifRead == true) {
double celcius = Double.parseDouble(celciusValue);
celcius = celcius * 9 / 5 + 32;
pw.println(celcius);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("dload")) {
OutputStream outToClient = client.getOutputStream();
if (outToClient != null) {
File myFile = new File("C:\\ftp\\pic.png");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0,
mybytearray.length);
outToClient.flush();
outToClient.close();
bis.close();
fis.close();
} catch (IOException ex) {
// Do exception handling
}
System.out.println("test");
}
}
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("quit")) {
client.close();
break;
}
// if (msgFromClient != null
// && !msgFromClient.equalsIgnoreCase("bye")) {
// OutputStream clientOut = client.getOutputStream();
// PrintWriter pw = new PrintWriter(clientOut, true);
// String ansMsg = "Hello, " + msgFromClient;
// pw.println(ansMsg);
// }
// Close sockets
if (msgFromClient != null
&& msgFromClient.equalsIgnoreCase("bye")) {
server.close();
client.close();
break;
}
msgFromClient = null;
}
} catch (IOException ie) {
}
}
}
Client:
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String args[]) {
boolean isConnected = true;
Socket client = null;
int portnumber = 1234; // Default port number we are going to use
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
try {
String msg = "";
// Create a client socket
client = new Socket("127.0.0.1", 1234);
System.out.println("Client socket is created " + client);
// Create an output stream of the client socket
OutputStream clientOut = client.getOutputStream();
PrintWriter pw = new PrintWriter(clientOut, true);
// Create an input stream of the client socket
InputStream clientIn = client.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
clientIn));
// Create BufferedReader for a standard input
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
while (isConnected == true) {
System.out
.println("Commands: \n1. TIME\n2. DATE\n3. C2F\n4. MAX\n5. SUM\n6. DLOAD\n7. QUIT");
// Read data from standard input device and write it
// to the output stream of the client socket.
msg = stdIn.readLine().trim();
pw.println(msg);
// Read data from the input stream of the client socket.
if (msg.equalsIgnoreCase("dload")) {
byte[] aByte = new byte[1];
int bytesRead;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (clientIn != null) {
try {
FileOutputStream fos = new FileOutputStream("C:\\ftp\\pic.png");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = clientIn.read(aByte, 0, aByte.length);
do {
baos.write(aByte, 0, bytesRead);
bytesRead = clientIn.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
System.out.println("File is successfully downloaded to your selected directory"+ "\n" +"*-----------------*"+ "\n" );
} catch (IOException ex) {
System.out.println("Couldn't dowload the selected file, ERROR CODE "+ex);
}
}
}else{
System.out.println("Message returned from the server = "
+ br.readLine());
}
if (msg.equalsIgnoreCase("bye")) {
pw.close();
br.close();
break;
}
}
} catch (Exception e) {
}
}
}
debugged your code and have two hints:
1)
don't surpress your exceptions. handle them! first step would to print your stacktrace and this question on SO wouldn't ever be opened ;-) debug your code!
2)
outToClient.flush();
outToClient.close(); //is closing the socket implicitly
bis.close();
fis.close();
so in your second call the socket on server-side will already be closed.
first thing:
if (args.length >= 1) {
portnumber = Integer.parseInt(args[0]);
}
This can throw a NumberFormatException, and because args[0] is passed by the user you should handle this.
reading the code also this gave me a problem:
double DoubleValue = Double.parseDouble(value); // LINE 104
Throwing a NumberFormatException when I give c2f as command to the server. You definitively need to handle this exception anywhere in your code and give proper answer to the client, something like:
try{
double DoubleValue = Double.parseDouble(value);
}catch(NumberFormatException e){
// TELL THE CLIENT "ops, the number you inserted is not a valid double numer
}
(in short example, starting from this you have to enlarge the code)
while (isConnected == true) {
I cannot see it! why not use this?
while (isConnected) {
if (msgFromClient != null && msgFromClient.equalsIgnoreCase("sum")){
can be:
if("sum".equalsIgnoreCase(msgFromClient)){
in this case you have no problem with the NullPointerException. (if msgFromClient is null the statement is false).
By the way, date and time command are working fine for me. Check the others.
To fix dload i think you have to delete the line:
outToClient.close();
(EDIT: sorry to maxhax for the same answr, didn't see your answer while writing this)

Categories

Resources