transformer to socket not working - java

Its driving me nuts trying days to grind this problem.
I am writing a java server to work with an android application. They communicate text string and xml.
Currently simple socket communication seems fine, however it breaks down when I tried to use transformer instead of simple println.
Server code as below
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class javamultithreadedserver implements Runnable {
Socket csocket;
static int listenport = 6021;
public static final String endOfCom = "endofcom";
String connectionname;
public javamultithreadedserver(Socket csocket, String connectionname) {
this.csocket = csocket;
this.connectionname = connectionname;
}
public static void main(String[] args) throws Exception {
int listentoport = 0;
//System.out.println(args.length);
if (args.length == 1){
listentoport = Integer.parseInt(args[0]);
} else{
listentoport = listenport;
}
ServerSocket ssock = new ServerSocket(listentoport);
System.out.println("Listening at port " + listentoport);
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected. from: " + sock.getInetAddress().getHostAddress() + " " + sock.getInetAddress().getHostName() + " port: " + sock.getPort() + " " + sock.getInetAddress().getCanonicalHostName());
new Thread(new javamultithreadedserver(sock, sock.getInetAddress().getHostAddress() + " " + sock.getInetAddress().getHostName() + " " + sock.getInetAddress().getCanonicalHostName())).start();
}
}
#Override
public void run() {
try {
PrintWriter out = new PrintWriter(csocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(csocket.getInputStream()));
PrintStream pstream = new PrintStream (csocket.getOutputStream(), true);
String inputLine, outputLine;
System.out.println(connectionname + ": listening for query information.");
while ((inputLine = in.readLine()) != null) {
System.out.println(connectionname + ": " + inputLine);
//out.write("received something");
DBQuery q = new DBQuery(inputLine + DBQuery.regexsplit + "connectionname" + DBQuery.regexsplit + connectionname);
DOMSource dmsource = q.returns();
***//StreamResult consoleResult = new StreamResult(System.out); //debug***
StreamResult consoleResult = new StreamResult(pstream);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Thread.sleep(100);
***transformer.transform(dmsource, consoleResult);***
//out.println("println this is a testprogram"); // client receive ok
pstream.flush();
System.out.println(connectionname + ": reply sent.");
if (inputLine == endOfCom){
System.out.println(connectionname + ": is satisfied and terminated communication.");
break;
}
}
pstream.close();
csocket.close();
}catch (IOException e) {
System.out.println(e);
}catch (Exception e) {
System.out.println(e);
}
}
}
And the android client code as below:
public void run() {
if (barcode.length() > 0) {
Socket socket = null;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
socket.setSoTimeout(10000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write(barcode + ENDL);
if(out.checkError()){
showToUI("PrintWriter had error");
} else {
showToUI("Query sent");
}
int i = 0;
while (true) {
try{
if (**(serverResponse = in.readLine()) != null**) {
if(serverResponse == endOfCom){
Log.i("communicated all data", "bye");
out.write(endOfCom + ENDL);
break;
} else{
}
Log.i("server says", serverResponse);
}
//Log.i("server says", (serverResponse == null? "null" :serverResponse ));
}catch(SocketTimeoutException e){
showToUI(barcode + ": Server did not respond in time");
if (i++ > 2) {
break;
}
}
}
} catch (final UnknownHostException e1) {
showToUI(e1.toString());
} catch (final IOException e1) {
showToUI(e1.toString());
} finally{
try {
socket.close();
} catch (IOException e) {
showToUI(e.toString());
}
}
}else{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Please enter something in barcode", Toast.LENGTH_SHORT).show();
}
});
}
}
I have tested that the xml result returned was ok, if the Stream Result was set to System.out instead of the PrintStream pstream, everything prints perfectly to the console.
However with or without pstream.flush(), client received no response at (serverResponse = in.readLine()) != null.
Also the PrintWriter out which was based on the same Socket socket of pstream successfully gave feedback to the client. When out.println("println this is a testprogram"); was called, the client received log at the Log.i("server says", serverResponse); line OK.
One thing to note is that the reply is usually quite long, can be up to 65536 characters or even more, I do not know if that has any implication, I have tried to create a Buffered reader on the android app larger than the replying xml, it still did not work. The machines are communicating on local network, java server program is running on a different machine from the android emulator.
Any help is appreciated, this had been going on for days and nowhere.

readLine() won't return null until the peer closes the connection. And when it does return null, you need to break out of the loop. And don't compare string s with ==.

Related

Trouble writing to OutputStream socket

I am writing a simple web server program for class that sends files to the web browser on request. I have written as much as I could. The difficulty is getting the data written to the OutputStream. I don't know what I am missing. I couldn't get the simple request to show up on the web browser.
I wrote it to the "name" OutputStream but when I reload the tab in the browser with the URL: "http://localhost:50505/path/file.txt" or any other like that "localhost:50505" it doesn't show up what I wrote to the OutputStream "name". It is supposed to show that.
package lab11;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
public class main {
private static final int LISTENING_PORT = 50505;
public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(LISTENING_PORT);
}
catch (Exception e) {
System.out.println("Failed to create listening socket.");
return;
}
System.out.println("Listening on port " + LISTENING_PORT);
try {
while (true) {
Socket connection = serverSocket.accept();
System.out.println("\nConnection from "
+ connection.getRemoteSocketAddress());
handleConnection(connection);
}
}
catch (Exception e) {
System.out.println("Server socket shut down unexpectedly!");
System.out.println("Error: " + e);
System.out.println("Exiting.");
}
}
public static void handleConnection(Socket sok) {
try {
// Scanner in = new Scanner(sok.getInputStream());
InputStream one = sok.getInputStream();
InputStreamReader isr = new InputStreamReader(one);
BufferedReader br = new BufferedReader(isr);
String rootDirectory = "/files";
String pathToFile;
// File file = new File(rootDirectory + pathToFile);
StringBuilder request = new StringBuilder();
String line;
line = br.readLine();
while (!line.isEmpty()) {
request.append(line + "\r\n");
line = br.readLine();
}
// System.out.print(request);
String[] splitline = request.toString().split("\n");
String get = null;
String file = null;
for (String i : splitline) {
if (i.contains("GET")) {
get = i;
String[] splitget = get.split(" ");
file = splitget[1];
}
}
}
OutputStream name = sok.getOutputStream();
Boolean doesexist = thefile.exists();
if (doesexist.equals(true)) {
PrintWriter response = new PrintWriter(System.out);
response.write("HTTP/1.1 200 OK\r\n");
response.write("Connection: close\r\n");
response.write("Content-Length: " + thefile.length() + "\r\n");
response.flush();
response.close();
sendFile(thefile, name);
} else {
System.out.print(thefile.exists() + "\n" + thefile.isDirectory() + "\n" + thefile.canRead());
}
}
catch (Exception e) {
System.out.println("Error while communicating with client: " + e);
}
finally { // make SURE connection is closed before returning!
try {
sok.close();
}
catch (Exception e) {
}
System.out.println("Connection closed.");
}
}
private static void sendFile(File file, OutputStream socketOut) throws
IOException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(socketOut);
while (true) {
int x = in.read(); // read one byte from file
if (x < 0)
break; // end of file reached
out.write(x); // write the byte to the socket
}
out.flush();
}
}
So, I don't know what I really did wrong.
When I load the browser with localhost:50505 it just says can't connect or localhost refused to connect.
You are writing the HTTP response in System.out. You should write it in name, after the headers, in the body of the response. You probably want to describe it with a Content-Type header to make the receiver correctly show the file.

how to run config server when the port is args[0] in eclipse

This is my simple server program with java's ServerSocket class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServerSocketTest {
public static void main(String[] args) {
while (true)
{
try {
if (args.length != 1) {
System.err.println("Usage: java StartServer <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for client...on " + port);
Socket client = server.accept();
System.out.println("Client from /" + client.getInetAddress() + " connected.");
BufferedReader rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
Writer out = new OutputStreamWriter(client.getOutputStream());
String nameClient = rdr.readLine();
System.out.println("Client " + nameClient + " wants to start a game.");
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
I am trying to run config the server
but it keeps on saying this "Usage: java StartServer ".
I want to know how can I config the port when the port is args[0].
This is in Eclipse, by the way.
If it keeps saying "Usage: java StartServer" it therefore means this code
System.err.println("Usage: java StartServer <port>");
Is always been executed which means the condition
args.length != 1
Is always true. This could mean args.length = 0 or args.length > 1
Did you make eclipse pass the port number when running your application? That is did you configure any command line arguments to be used? I'm not a user eclipse so I can't help you here. See if this tutorial is helpful http://www.concretepage.com/ide/eclipse/how-to-pass-command-line-arguments-to-java-program-in-eclipse or you could try to find some other tutorial.
Also make sure you didn't pass too many arguments than is required because that will also make the condition to return true. Just pass as many arguments to make the condition args.length != 1 fail which is having 1 argument.
You can also see this question with help configuring command line arguments in eclipse.
This is my practice for you.
Copy and complete your code.
Select menu clicking right button of your mouse, Run > Run Configurations
Select Arguments tab and type a port number whatever you want your server to wait for client connection then, run it.
Test it with your client socket program.
This is my practice using client socket programming.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SimpleClientSocketTest {
public static void main(String[] args) {
BufferedReader rdr = null;
Socket sock = null;
PrintWriter out = null;
try{
sock = new Socket("localhost", 9999);
rdr = new BufferedReader(new InputStreamReader(sock.getInputStream(), "UTF-8"));
out = new PrintWriter(sock.getOutputStream(), true);
String toServer = "hello...";
out.println(toServer + "i wants to start a game.");
String fromServer = rdr.readLine();
System.out.println("server: " + fromServer);
if(fromServer == null) System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
finally
{
try {
rdr.close();
out.flush();
out.close();
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Send a message to the server first,
out.println(toServer + "i wants to start a game.");
then, receive from the server.
String fromServer = rdr.readLine();
System.out.println("server: " + fromServer);
There is one more thing to tell you about your server program.
This is a customized version of yours.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServerSocketTest {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java StartServer <port>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
ServerSocket server = null;
try {
server = new ServerSocket(port);
} catch (IOException e2) {
e2.printStackTrace();
}
while (true) {
BufferedReader rdr = null;
PrintWriter out = null;
int clientConnectionCnt = 0;
try {
System.out.println("1Waiting for client...on " + port);
Socket client = server.accept();
if(client.isConnected())
{
System.out.println("Client from /" + client.getInetAddress() + " connected.");
String nameClient = null;
try {
rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
out = new PrintWriter(client.getOutputStream(), true);
System.out.println("clientConnectionCnt....." + clientConnectionCnt++);
nameClient = rdr.readLine();
out.println("Yes, You can");
if(nameClient == null) break;
System.out.println("Client: " + nameClient);
} catch (IOException e) {
e.printStackTrace();
break;
} finally {
out.flush();
rdr.close();
out.close();
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
try {
server.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
First, you should create a server socket outside of while statement not in a while.
try {
server = new ServerSocket(port);
} catch (IOException e2) {
e2.printStackTrace();
}
Just wait in a while statement util client socket accepting.
while (true) {
.... skip ...
System.out.println("1Waiting for client...on " + port);
Socket client = server.accept();
Then, create in/out stream of client socket.
rdr = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
out = new PrintWriter(client.getOutputStream(), true);
Finally, read and write a message with the socket's stream.
nameClient = rdr.readLine();
out.println("Yes, You can");
Regards, Rach.

iterative dictionary server in java

what it do..
1. an iterative dictionary server that is listening clients requests..
2. connection will be established..
3. server will accept input string from client..
4. then server will search meaning of string from a file..
5. then server will return meaning to the client..
problem is with the while loop of server.. if it finds word it will send that word's meaning to client..fine.. but if word is not found... this
if(d.equals(null)){
input="No knowledge";
out.println(input);
out.flush();
}
doesn't execute... client says null and server says null exception...
what i am doing wrong here... i'm not getting it...!!
i have tried to changed this code...
client-server online dictionary program in java
client:
import java.io.;
import java.net.;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class DCC1 {
public static void main(String[] args) throws IOException {
final int PORT = 8888;
Socket s = null;
PrintWriter out = null;
try {
s = new Socket("localhost", PORT);
out = new PrintWriter(s.getOutputStream()); // Output stream to the server
}
catch (UnknownHostException ex) {
System.err.println("Unknown host: " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
catch (IOException ex) {
System.err.println("Cannot get I/O for " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
Scanner user = new Scanner(System.in); // Scanning for user input
System.out.print("Enter String: ");
String input;
input = user.next(); // Hold the input from the user
out.println(input); // Send it to the server
out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream( )));
System.out.println(br.readLine());
out.close();
s.close();
}
}
server:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class DSC1
{
public static void main(String[] args) throws IOException
{
final int PORT = 8888;
final String FILE_NAME = "dictionary.dat";
ServerSocket server = new ServerSocket(PORT);
Socket s = null;
PrintWriter out = null;
Scanner in = null;
FileInputStream fin = null;
ObjectInputStream oin = null;
while (true)
{
try
{
s = server.accept();
}
catch (IOException ex)
{
System.err.println("Accept failed");
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
System.out.println("Accepted connection from client");
try
{
in = new Scanner(s.getInputStream()); // Input stream from the client
out = new PrintWriter(s.getOutputStream()); // Output stream to the client
String temp = in.next(); // String holding the word sent from the client
System.out.println("From the client " + temp);
String input = null;
fin = new FileInputStream(FILE_NAME);// The dictionary file
oin = new ObjectInputStream(fin);
dictionary d = (dictionary)oin.readObject();
while(d!= null)
{
System.out.println("in loop...");
if(d.name.equals(temp)){
input=d.meaning;
d.printDic();
out.println(input);
out.flush();
break;
}
d = (dictionary)oin.readObject();
if(d.equals(null))
{
input="No knowledge";
out.println(input);
out.flush();
}
}
}
catch (ClassNotFoundException|IOException ex)
{
System.err.println("Exception: " + ex.getMessage());
System.out.println("Closing connection with client");
in.close();
System.exit(1);
}
in.close();
}
}
}
Don't use d.equals(null). If you want to check if d is null, just do if (d==null).
Why? There's no way this can return true, so probably that's the reason why this code never executes and you don't get what you expect.

Login server web app java

Hi I am writing a basic login server using message passing . What my server does is it receives the message from some client checks in the database which is a file and accordingly sends back the reply so what is happening is whenever I send the message from telnet i can see that my server is accepting it and replying to it but it is not accepting a message again. Below is my code and this is no homework
package login;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamCorruptedException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class Login {
public static void main(String[] args) {
Login login = new Login();
new Thread(login.new ServerTask(null)).start();
new Thread(login.new ClientTask("clientstart")).start();
}
public String login(String userName, String password, String memberId) {
System.out.println("Entering login");
boolean match = false;
try {
// created an file input stream and a buffered reader stream to read
// from the files
FileInputStream inputStream = new FileInputStream(
"/home/rahulroc18/Desktop/database.txt");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String strLine;
String[] dataReader;
dataReader = new String[10];
String readData = "";
// Loop through the end of the file and read the data line by line
// in order to store it into a string for further storage in the
// memory
while ((strLine = bufferedReader.readLine()) != null) {
readData = readData + strLine + ":";
}
// split the string to store user name and password for storing in
// an array in alternate positions
dataReader = readData.split(":");
// System.out.println(dataReader.length);
// loops through the array and checks the user name and passwords
// for
// the correct match sends the login successful if password is
// incorrect sends message password in correct else for no match
// sends check your credentials
for (int i = 0; i < dataReader.length; i++) {
if (userName.equals(dataReader[i])) {
match = true;
if (password.equals(dataReader[i + 1])) {
String message;
message = "Login Successfull" + " : " + userName
+ " : " + password + " : " + memberId;
System.out
.println("Sending success message to client !!!");
return message;
// send the transactions and data of whatever
// conversation has taken place till now
// System.out.println("for loop of login");
// System.out.println("message to be sent back is: " +
// message);
// new Thread(new ClientTask(message)).start();
// Send message to all users that this new user has
// joined the conversation
// System.out.println(message);
} else {
String message = "";
message = "Password Incorrect";
System.out.println("message to be sent back is: "
+ message);
System.out.println(message);
return message;
}
}
}
if (!match) {
String message = "";
message = "check your credentials";
System.out.println("message to be sent back is: " + message);
return message;
}
inputStream.close();
} catch (FileNotFoundException f) {
f.printStackTrace();
} catch (IOException e) {
System.out.println(e);
}
System.out.println("Exiting login");
return null;
}
class ServerTask implements Runnable {
String msgReceived;
public ServerTask(String message) {
msgReceived = message;
}
#Override
public void run() {
System.out.println("Server task started !!!");
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10000);
Socket clientSocket = null;
while (true) {
clientSocket = serverSocket.accept();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
msgReceived = buffer.readLine();
if (msgReceived.substring(0, 5).equals("login")) {
System.out.println("in if condition of server task");
String finalMessage = login(
msgReceived.substring(5, 10),
msgReceived.substring(10, 15),
msgReceived.substring(15));
System.out.println("finalMessage is " + finalMessage);
OutputStream os = clientSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(finalMessage);
bw.flush();
} else {
System.out.println("************");
String message = "Client started successfully and startup message is recieved \n";
OutputStream os = clientSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(message);
bw.flush();
}
}
} catch (StreamCorruptedException sc) {
System.out.println(sc);
} catch (IOException i) {
i.printStackTrace();
}
}
}
class ClientTask implements Runnable {
String msgToSend;
public ClientTask(String message) {
msgToSend = message;
}
#Override
public void run() {
Socket sock = new Socket();
try {
sock = new Socket("127.0.0.1", 10000);
OutputStreamWriter out = new OutputStreamWriter(
sock.getOutputStream());
BufferedWriter buffer = new BufferedWriter(out);
buffer.write(msgToSend);
buffer.flush();
sock.close();
System.out.println("In client task .... message is "
+ msgToSend);
} catch (SocketException s) {
} catch (IOException i) {
}
}
}
}
Your code contains lots of bugs.
You have to create separate class for the client and the server.Now in your code what is happening is that suppose what happen if your client thread will start first rather than the server thread.
clientSocket = serverSocket.accept(); this will come in your main thread and whatever the object you receive from serverSocket.accept(); will come as a parameter in other thread.So your server will wait for the request from client in main thread and your newly created thread will handle the client.

Tricky NullPointerException while sending a file to a client

I am working on a simple server in Java that should have a capability of transferring a file across computers. I am getting a NullPointerException on line 77 of Protocol.class. Here is the stack:
java.lang.NullPointerException
at Protocol.processInput(Protocol.java:77)
at Server.main(Server.java:41)
Why does this happen? There is no null references on line 77!
Client.java:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Client {
private static boolean filein = false;
private static ArrayList<String> fln = new ArrayList<>();
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java Client <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 = null;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("#file")) { filein = true;
fromUser = "";}
else if(fromServer.equals("#end#")) {
filein = false;
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String fname = chooser.getSelectedFile().getAbsolutePath();
File f = new File(fname);
f.createNewFile();
PrintWriter p = new PrintWriter(f);
for(int i = 0; i < fln.size(); i++) {
p.println(fln.get(i));
}
p.close();
JOptionPane.showMessageDialog(null, "File saved!");
}
}
else if (filein == true) {
fln.add(fromServer);
System.out.println(fln.get(fln.size() - 1));
}
if (fromServer.equals("Bye."))
break;
if (!filein) fromUser = stdIn.readLine();
else if (filein) fromUser = "#contintueFileRun";
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);
}
}
}
Server.java:
import java.io.*;
import java.net.*;
import static java.lang.System.out;
/**
* Title: FTP Server
* #author Galen Nare
* #version 1.0
*/
public class Server {
public static void main(String[] args) throws IOException {
out.println("Starting server!");
if (args.length != 1) {
System.err.println("Usage: java Server <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
Protocol kkp = new Protocol();
outputLine = kkp.processInput("");
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.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());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And finally, Protocol.java:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Protocol {
enum ServerState {
STARTING,
WAITING
}
ArrayList<String> lns;
boolean fileout = false;
int i = 0;
private ServerState state = ServerState.STARTING;
public String processInput(String theInput) throws Exception {
String theOutput = "";
if (state == ServerState.STARTING) {
theOutput = "Hello, Client!";
state = ServerState.WAITING;
}
if (!theInput.equals("")) {
if(theInput.length() > 10 && theInput.startsWith("e")) {
if (theInput.substring(0,11).equalsIgnoreCase("executecmd ")) {
theOutput = theInput.substring(11);
System.out.println(theOutput);
try {
#SuppressWarnings("unused")
Process child = Runtime.getRuntime().exec(theInput.substring(11));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
theOutput = "Executed " + theInput.substring(11) + ".";
}
} else if (theInput.equalsIgnoreCase("stop")) {
theOutput = "Stopping Server!";
System.exit(0);
} else if (theInput.equalsIgnoreCase("executecmd")) {
theOutput = "Usage: executecmd <command [-options]>";
} else if (theInput.equalsIgnoreCase("getfile")) {
theOutput = "Usage: getfile <file>";
} else if(theInput.length() > 7 && theInput.startsWith("g")) {
System.out.println("in");
if (theInput.substring(0,8).equalsIgnoreCase("getfile ")) {
theOutput = theInput.substring(8);
File f = new File(theInput.substring(8));
Scanner scan = new Scanner(f);
ArrayList<String> lns = new ArrayList<>();
while(scan.hasNext()) {
lns.add(scan.nextLine());
}
for (int i=0; i < lns.size(); i++) {
System.out.println(lns.get(i));
}
scan.close();
lns.add("#end#");
theOutput = "#file";
fileout = true;
}
} else if (fileout && i < lns.size()) {
theOutput = lns.get(i);
i++;
} else if (fileout && i == lns.size()) {
i = 0;
fileout = false;
} else {
theOutput = "That is not a command!";
}
}
System.out.print(theOutput);
return theOutput;
}
}
Thanks in advance!
You're never initializing lns in Protocol, so it's always a null reference. You may be able to get away with just changing the declaration to:
private List<String> lns = new ArrayList<String>();
(I've made it private and changed the type to List just out of habit...)
You should also consider giving it a more readable name - is it meant to represent lines? If so, call it lines!
(Next, consider why you weren't able to diagnose this yourself. Did you step through this in the debugger? Why did you think there were no null references on line 77? What diagnostic steps did you take in terms of adding extra logging etc? It's important to use errors like this as a learning experience to make future issues more tractable.)

Categories

Resources