java.util.NoSuchElementException: No line found error java - java

Keep getting this error
"java.util.NoSuchElementException: No line found error java"
and searched through code so many times and cant see to find problems heres my files can anyone help?
Am currently doing this as an assignment and am trying to transfer it from unthreaded to threaded and in the process came up with this error!!
This is the Client class
package Client;
import core.Email;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Scanner;
public class EmailClient {
public static void main(String[] args) {
try
{
// Step 1 (on consumer side) - Establish channel of communication
Socket dataSocket = new Socket("localhost", EmailServiceDetails.LISTENING_PORT);
// Step 3) Build output and input objects
OutputStream out = dataSocket.getOutputStream();
PrintWriter output = new PrintWriter(new OutputStreamWriter(out));
InputStream in = dataSocket.getInputStream();
Scanner input = new Scanner(new InputStreamReader(in));
Scanner keyboard = new Scanner(System.in);
String message = "";
while(!message.equals(EmailServiceDetails.END_SESSION))
{
displayMenu();
int choice = getNumber(keyboard);
String response = "";
if(choice >=0 && choice < 3)
{
switch (choice)
{
case 0:
message = EmailServiceDetails.END_SESSION;
// Send message
output.println(message);
output.flush();
response = input.nextLine();
if(response.equals(EmailServiceDetails.SESSION_TERMINATED))
{
System.out.println("Session ended.");
}
break;
case 1:
message = sendEmail(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.SUCCESSFUL_ADD))
{
System.out.println("Email sent successfully");
}
else if(response.equals(EmailServiceDetails.UNSUCCESSFUL_ADD))
{
System.out.println("Sorry, the email could not be sent at this time.");
}
break;
case 2:
message = viewUnread(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.NO_UNREAD))
{
System.out.println("No unread mails found for that account.");
}
else
{
ArrayList<Email> unreadMails = EmailServiceDetails.parseEmailList(response);
System.out.println("Unread Emails:");
for(Email e: unreadMails)
{
System.out.println(e);
}
}
break;
}
if(response.equals(EmailServiceDetails.UNRECOGNISED))
{
System.out.println("Sorry, that request cannot be recognised.");
}
}
else
{
System.out.println("Please select an option from the menu");
}
}
System.out.println("Thank you for using the Email system.");
dataSocket.close();
}catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
public static void displayMenu()
{
System.out.println("0) Exit");
System.out.println("1) Send an email");
System.out.println("2) View all unread mails");
}
public static int getNumber(Scanner keyboard)
{
boolean numberEntered = false;
int number = 0;
while(!numberEntered)
{
try{
number = keyboard.nextInt();
numberEntered = true;
}
catch(InputMismatchException e)
{
System.out.println("Please enter a number.");
keyboard.nextLine();
}
}
keyboard.nextLine();
return number;
}
public static String sendEmail(Scanner keyboard)
{
System.out.println("Please enter the sender of this email:");
String sender = keyboard.nextLine();
// Get recipient information
String anotherRecipient = "Y";
ArrayList<String> recipients = new ArrayList();
while(anotherRecipient.equalsIgnoreCase("Y"))
{
System.out.println("Enter the recipient's email address:");
String recipient = keyboard.nextLine();
recipients.add(recipient);
System.out.println("Would you like to add another recipient? ('Y' for yes and 'N' for no)");
anotherRecipient = keyboard.nextLine();
}
System.out.println("Please enter the email subject:");
String subject = keyboard.nextLine();
System.out.println("Please enter the message body:");
String body = keyboard.nextLine();
// Get attachment information
ArrayList<String> attachments = new ArrayList();
System.out.println("Would you like to enter an attachment ('Y' to add and 'N' to continue)");
String anotherAttachment = keyboard.nextLine();
while(anotherAttachment.equalsIgnoreCase("Y"))
{
System.out.println("Enter the attachment information:");
String attachment = keyboard.nextLine();
attachments.add(attachment);
System.out.println("Would you like to add another attachment? ('Y' for yes and 'N' to Continue)");
anotherAttachment = keyboard.nextLine();
}
long timestamp = new Date().getTime();
String response = null;
Email e = null;
if(attachments.size() > 0)
{
e = new Email(sender, recipients, subject, body, timestamp, attachments);
}
else
{
e = new Email(sender, recipients, subject, body, timestamp);
}
response = EmailServiceDetails.ADD_MAIL + EmailServiceDetails.COMMAND_SEPARATOR + EmailServiceDetails.formatEmail(e);
return response;
}
public static String viewUnread(Scanner keyboard)
{
System.out.println("Please enter the name of the email account you wish to see unread mail for:");
String recipient = keyboard.nextLine();
String response = EmailServiceDetails.VIEW_UNREAD + EmailServiceDetails.COMMAND_SEPARATOR + recipient;
return response;
}
}
--------------------------------------------------------------------------------
This is Server
---------------
package Server;
import Server.Commands.Command;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EmailServer {
public static void main(String[] args) {
try{
// Set up a connection socket for other programs to connect to
ServerSocket listeningSocket = new ServerSocket(EmailServiceDetails.LISTENING_PORT);
// Create the list of emails to be stored and worked with
EmailStore emails = new EmailStore();
boolean continueRunning = true;
int threadCount = 0;
while(continueRunning)
{
// Step 2) wait for incoming connection and build communications link
Socket dataSocket = listeningSocket.accept();
threadCount++;
System.out.println("The server has now accepted " + threadCount + " clients");
// Step 3) Build thread
// Thread should be given:
// 1) a group to be stored in
// 2) a name to be listed under
// 3) a socket to communicate through
// 4) Any extra information that should be shared
EmailThread newClient = new EmailThread (emails, dataSocket.getInetAddress()+"", dataSocket,threadCount);
newClient.start();
}
listeningSocket.close();
}
catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
}
}
--------------------------------------------------------------------------------
This is ServerThread
---------------
package Server;
import Server.Commands.Command;
import Server.EmailStore;
import core.EmailServiceDetails;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;
/**
*
* #author User
*/
public class EmailThread extends Thread {
private Socket dataSocket;
private Scanner input;
private PrintWriter output;
private int number;
private EmailStore emails;
public EmailThread(EmailStore emails,String name, Socket dataSocket, int number) {
try {
// Save the data socket used for communication between the thread and the Client
this.dataSocket = dataSocket;
// Save the id of the thread to identify output
// Save the id of the thread to identify output
this.number = number;
input = new Scanner(new InputStreamReader(this.dataSocket.getInputStream()));
// Create the stream for writing to the Client
output = new PrintWriter(this.dataSocket.getOutputStream(), true);
} catch (IOException e) {
System.out.println("An exception occurred while setting up connection links for a thread: " + e.getMessage());
}
}
#Override
public void run() {
{
String incomingMessage = "";
String response;
try {
while (!incomingMessage.equals(EmailServiceDetails.END_SESSION)) {
// Wipe the response to make sure we never use an old value
response = null;
// take in information from the client
incomingMessage = input.nextLine();
System.out.println("Received message: " + incomingMessage);
// Break up information into components
String[] components = incomingMessage.split(EmailServiceDetails.COMMAND_SEPARATOR);
// Confirm that the command was correctly formatted
// Did it include more than just the command text?
if (components.length > 1) {
CommandFactory factory = new CommandFactory();
// Figure out which command was sent by the client
// I.e. what does the client want to do?
Command command = factory.createCommand(components[0]);
// Take the remaining text the client sent (i.e. all the information provided)
// and execute the requested action (e.g. store the new mail, get all sent mails etc)
response = command.createResponse(components[1], emails);
} else if (components[0].equals(EmailServiceDetails.END_SESSION)) {
response = EmailServiceDetails.SESSION_TERMINATED;
} else {
// If information was missing, set the response to inform the
// client that the command wasn't recognised
response = EmailServiceDetails.UNRECOGNISED;
}
// Send back the computed response
output.println(response);
output.flush();
}
} catch (Exception e) {
System.out.println("An exception occurred while communicating with client #" + number + ": " + e.getMessage());
} finally {
try {
// Shut down connection
System.out.println("\n* Closing connection with client #" + number + "... *");
dataSocket.close();
} catch (IOException e) {
System.out.println("Unable to disconnect: " + e.getMessage());
System.exit(1);
}
}
}
}
}
--------------------------------------------------------------------------------
This is EmailStore
---------------
package Server;
import core.Email;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class EmailStore
{
private ArrayList<Email> emailList = new ArrayList();
public boolean addMail(Email newEmail)
{
return emailList.add(newEmail);
}
public boolean removeMail(Email mailToBeDeleted)
{
return emailList.remove(mailToBeDeleted);
}
public ArrayList<Email> findEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient
.filter(email -> email.getRecipients().contains(recipient))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
public ArrayList<Email> findEmailBySender(String sender)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails matching the specified sender
.filter(email -> email.getSender().equals(sender))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
// Methods to mark emails as read
// Provide a version that marks multiple mails as read AND a version that
// marks a single email as read
public void markMultipleAsRead(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsRead(e);
}
}
public void markAsRead(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsRead(true);
}
}
// Methods to mark emails as spam
// Provide a version that marks multiple mails as spam AND a version that
// marks a single email as spam
public void markAsSpam(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsSpam(true);
}
}
public void markMultipleAsSpam(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsSpam(e);
}
}
public ArrayList<Email> findUnreadEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient AND the email is not unread
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
}
-------
Help Appreciated
-
----------
Help would be great appreciated as the frustration levels are at a high!!

This answer is a wild guess but in case 1 of the switch statement of the main method you are calling the input.nextLine() scanner which it might not contain information at that time. It is possible that you have to check if data arrived by using the hasNext() method first.
Also in the last method when you are collecting the email classes you don't really need to cast. It can be done like this:
results = emailList.stream()
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
.collect(Collectors.toCollection(ArrayList::new));

Related

How can I make my server recognize more than 1 user's login info in java?

Now I do realize there are lots of the same question but even after reading the answers I seem not to undertsand. So here is the code and I'll explain the problem.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server implements Runnable {
String firstName;
String lastName;
String password;
private ArrayList<ConnectionHandler> connections;
private ServerSocket server;
private boolean done;
private ExecutorService pool;
public Server() {
connections = new ArrayList<>();
done = false;
}
#Override
public void run() {
try {
server = new ServerSocket(9999);
pool = Executors.newCachedThreadPool();
while (!done) {
Socket client = server.accept();
ConnectionHandler handler = new ConnectionHandler((client));
connections.add(handler);
pool.execute(handler);
}
} catch (Exception e) {
shutdown();
}
}
public void shutdown() {
try {
done = true;
pool.shutdown();
if (!server.isClosed()) {
server.close();
}
for (ConnectionHandler ch : connections) {
ch.shutdown();
}
} catch (IOException e) {
// ignore
}
}
class ConnectionHandler implements Runnable {
private Socket client;
private BufferedReader in;
private PrintWriter out;
public void broadcast(String message) {
for (ConnectionHandler ch : connections) {
if (ch != null) {
ch.sendMessage(message);
}
}
}
public ConnectionHandler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
out = new PrintWriter((client.getOutputStream()), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out.println("To register type 1,to sign in type 2");
//TODO:for loop so only answer is 1 or 2
String message = in.readLine();
switch (message) {
case "1":
out.println("In order to register please enter your first and last name then set a password.");
out.println("Enter first name:");
firstName = in.readLine();
out.println("Enter last name:");
lastName = in.readLine();
out.println("Finally please set a password.");
password = in.readLine();
//TODO: add parameters for passcode
out.println("Now please type 2 to login");
message = in.readLine();
if (message.equals("2")) {
//TODO: copy paste from line 104-x
}
case "2":
out.println("Please enter your first name:");
String messageLogInFN= in.readLine();
out.println("Please enter your last name:");
String messageLogInLN = in.readLine();
out.println("Enter your password:");
String messageLogInPass = in.readLine();
boolean adminAccount = (messageLogInFN.equals("admin") && messageLogInLN.equals("admin") && messageLogInPass.equals("admin123cat"));
if (adminAccount) {
//TODO: add admin permissions
}
boolean Authentication = ((messageLogInFN.equals(firstName) && messageLogInLN.equals(lastName) && messageLogInPass.equals(password)));
if (Authentication) {
out.println("Welcome " + firstName + " " + lastName + "!");
System.out.println(firstName + " " + lastName + " has logged in." );
} else
out.println("Your name or password incorrect!");
}
} catch (IOException e) {
shutdown();
}
}
public void sendMessage(String message) {
out.println(message);
}
public void shutdown() {
try {
in.close();
out.close();
if (!client.isClosed()) {
client.close();
}
} catch (IOException e) {
//ignore
}
}
}
public static void main(String[] args) {
Server server = new Server();
server.run();
}
So I am learning java and saw a tutorial on youtube for a chat room, I programed it following the tutorial, and then I wanted to have a chat room with accounts so I got to coding. Now here is the thing even though I am able to have several devices connected to the server when 2 accounts register the server forgets the first one so there can only be 1 account at the same time. What I am trying to do is have an account system where everyone has their own account that they log in with their first name, last name and passwords. But it doesnt seem to work. How can I make it so that the server doesn't forget all accounts except for the last one that registered?
Edit: Here is the client code if it helps.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client implements Runnable {
private boolean done;
private Socket client;
private BufferedReader in;
private PrintWriter out;
#Override
public void run() {
try {
client = new Socket("127.0.0.1", 9999);
out = new PrintWriter((client.getOutputStream()), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
InputHandler inHandler = new InputHandler();
Thread t = new Thread(inHandler);
t.start();
String inMessage;
while ((inMessage = in.readLine()) != null) {
System.out.println(inMessage);
}
} catch (IOException e) {
shutdown();
}
}
public void shutdown() {
done = true;
try {
in.close();
out.close();
if(!client.isClosed()) {
client.close();
}
} catch (IOException e) {
//ignore
}
}
class InputHandler implements Runnable {
#Override
public void run() {
try {
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
while (!done) {
String message = inReader.readLine();
if(message.equals("/quit")) {
out.println(message);
inReader.close();
shutdown();
} else {
out.println(message);
}
}
} catch (IOException e) {
shutdown();
}
}
}
public static void main(String[] args) {
Client client = new Client();
client.run();
}
}
Also as I said most of this isnt my code and I followed a yt tutorial.

How to fetch OTP From Mail and print on a text field?

I'm trying to automate registration on a website but that site send OTP to the email. so I need to fetch the OTP from the mail and print it to text field.
I am using this code but it's not showing unread message count and the OTP verification mail.
Can anyone help with how can I extract OTP from the email and submit it on the website ?
package MAVEN.GmailIMAP;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
public class Gmail3 {
public static void ReceiveMail(String FolderName,String SubjectContent, String emailContent, int lengthOfOTP){
String hostName = "imap.gmail.com";//change it according to your mail
String username = "test12345#gmail.com";//username
String password = "test12345"; //password
int messageCount;
int unreadMsgCount;
String emailSubject;
Message emailMessage;
String searchText=null ;
Properties sysProps = System.getProperties();
sysProps.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(sysProps, null);
Store store = session.getStore();
store.connect(hostName, username, password);
Folder emailBox = store.getFolder(FolderName);
emailBox.open(Folder.READ_ONLY);
messageCount = emailBox.getMessageCount();
System.out.println("Total Message Count: " + messageCount);
unreadMsgCount = emailBox.getNewMessageCount();
System.out.println("Unread Emails count:" + unreadMsgCount);
for(int i=messageCount; i>(messageCount-unreadMsgCount); i--)
{
emailMessage = emailBox.getMessage(i);
emailSubject = emailMessage.getSubject();
if(emailSubject.contains(SubjectContent))
{
System.out.println("OTP mail found");
String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(emailMessage.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String messageContent=emailContent;
String result = buffer.toString().substring(buffer.toString().indexOf(messageContent));
searchText = result.substring(messageContent.length(), messageContent.length()+lengthOfOTP);
System.out.println("Text found : "+ searchText);
emailMessage.setFlag(Flags.Flag.SEEN, true);
break;
}
emailMessage.setFlag(Flags.Flag.SEEN, true);
}
emailBox.close(true);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
System.out.println("OTP Not found ");
}
return searchText ;
}
public static void main(String[] args) {
ReceiveMail("FolderName","SubjectContent","One Time Password (OTP):",6);
}
}
Below Email body scanner should work for the input which you are looking for
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OtpRegex {
public static void main(String[] args) {
// String regex = "((is|otp|password|key|code|CODE|KEY|OTP|PASSWORD|Do).[0-9]{4,8}.(is|otp|password|key|code|CODE|KEY|OTP|PASSWORD)?)|(^[0-9]{4,8}.(is|otp|password|key|code|CODE|KEY|OTP|PASSWORD))";
String text = "To auth... \n\n869256\n\n Do is your login OTP. Treat this as confidential. Sharing it with anyone gives them full access to your Paytm Wallet. Paytm never calls to verify your OTP.";
Scanner sc = new Scanner(text);
int otp = -1;
String line = null;
while (sc.hasNextLine()) {
line = sc.nextLine().trim();
try{
otp = Integer.parseInt(line);
break;
} catch (NumberFormatException nfx) {
//Ignore the exception
}
}
System.out.println(otp);
}
}

StringIndexOutOfBoundsException in Java?

I try to run this java program which returns a webpage in my webroot folder
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class WebServer {
static ServerSocket requestListener;
static Socket requestHandler;
static Scanner requestReader, pageReader;
static DataOutputStream pageWriter;
static String HTTPMessage;
static String requestedFile;
public static int HTTP_PORT = 12346;
public static void main(String[] args) {
try {
requestListener = new ServerSocket(HTTP_PORT);
System.out.println("Waiting For IE to request a page:");
requestHandler = requestListener.accept();
System.out.println("Page Requested: Request Header:");
requestReader = new Scanner(new InputStreamReader(
requestHandler.getInputStream()));
//THis is the part where its throwing the error
int lineCount = 0;
do {
lineCount++; // This will be used later
HTTPMessage = requestReader.next();
System.out.println(HTTPMessage);
if (lineCount == 1) {
requestedFile = "WebRoot\\"
+ HTTPMessage.substring(5,
HTTPMessage.indexOf("HTTP/1.1") - 1);
requestedFile = requestedFile.trim();
}
// localhost:12346/default.htm
// HTTPMessage = requestReader.nextLine();
pageReader = new Scanner(new File(requestedFile));
pageWriter = new DataOutputStream(
requestHandler.getOutputStream());
while (pageReader.hasNext()) {
String s = pageReader.nextLine();
// System.out.println(s);
pageWriter.writeBytes(s);
}
// Tells the Browser we’re done sending
pageReader.close();
pageWriter.close();
requestHandler.close();
} while (HTTPMessage.length() != 0);
} catch (Exception e) {
System.out.println(e.toString());
System.out.println("\n");
e.printStackTrace();
}
}
}
and I get this error message. I am supposed to get a webpage in IE but all I get this error message.
Waiting For IE to request a page:
Page Requested: Request Header:
GET
java.lang.StringIndexOutOfBoundsException: String index out of range: -7
at java.lang.String.substring(Unknown Source)
at WebServer.main(WebServer.java:39)
This error is being thrown because the String 'HTTPMessage' does not contain the string 'HTTP/1.1'. Hence
HTTPMessage.indexOf("HTTP/1.1") => returns -1
So inside yoour substring function this is whats getting passed :
HTTPMessage.substring(5, -2);
Hence the error.
To solve this error, you should first try to check if HTTPMessage contains the required string and then try to compute the substring. Make the following change :
if (lineCount == 1 && HTTPMessage.indexOf("HTTP/1.1") != -1) {
requestedFile = "WebRoot\\"
+ HTTPMessage.substring(5,
HTTPMessage.indexOf("HTTP/1.1") - 1);
requestedFile = requestedFile.trim();
}

Chat server spitting out memory addresses. Not sure why

I'm currently working on a threaded server that allows multiple clients to connect and send messages to each other via "/username message" format. The server runs and my client class is able to connect successfully and be asked for a username, but once I attempt to send a message instead of receiving the output "To [username]: message" I receive "To: [memory address]: [memory address]" which I am confused about as I have not tried to print any objects.
Additionally, nothing is displayed on the client that is supposed to be on the other end of the message. The way I am handling the client threads is with an ArrayList that they are added to after they are created and started. The way I am attempting to send the messages to the clients on the other end is with a method in the server class that iterates through the ArrayList of client threads and outputs the message to the one with the corresponding name.
In advance: I am aware that my parseUserName and parseMessage methods are less than nice, but I've opted to let them sit until I can deal with the bigger problems. For reference, here is my server class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author
*/
public class ThreadedChatServer
{
//private ServerSocket server = new ServerSocket(5679);
private ServerSocket server;
ArrayList<ClientThread> clientThreads;
public ThreadedChatServer(ServerSocket s)
{
server = s;
clientThreads = new ArrayList<ClientThread>();
}
public void openServer() throws IOException
{
while(true)
{
Socket client = server.accept();
System.out.println("The server is connected to " + client.getInetAddress());
// starts a thread for this client
ClientThread c = new ClientThread(client, this);
c.start();
clientThreads.add(c);
}
}
// Iterates through the clientThreads ArrayList and prints the given message
// to the client whose name matches the "to" parameter.
public void sendMessage(String from, String to, String m)
{
for (int i = 0; i < clientThreads.size(); i++)
{
if (clientThreads.get(i).getUserName() != from &&
clientThreads.get(i).getUserName() == to)
{
clientThreads.get(i).toClient.println(m);
}
}
}
public static void main(String[] a) throws IOException
{
new ThreadedChatServer(new ServerSocket(5679)).openServer();
}
public class ClientThread extends Thread
{
private Socket s;
private String name;
private BufferedReader fromClient;
private PrintWriter toClient;
private ThreadedChatServer server;
public ClientThread(Socket c, ThreadedChatServer tc) throws IOException
{
s = c;
name = null;
fromClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
toClient = new PrintWriter(s.getOutputStream(), true);
server = tc;
}
public void run()
{
String s = null;
int size = 0;
char[] c = null;
try
{
toClient.println("Enter a username: ");
s = fromClient.readLine();
name = s;
// Accept/send messages from the user
while ((s = fromClient.readLine()) != null)
{
size = s.length();
c = new char[size];
for (int i = 0; i < size; i++)
{
c[i] = s.charAt(size - i - 1);
}
String output = c.toString();
String s2 = "To " + parseUserName(output) + ": "
+ parseMessage(output);
toClient.println(s2);
server.sendMessage(this.name, parseUserName(output),
parseMessage(output));
}
// Close the connection
fromClient.close();
toClient.close();
this.s.close();
clientThreads.remove(c);
} catch (IOException e) {e.printStackTrace();}
}
public String getUserName() {return name;}
public String parseUserName(String s)
{
Scanner in = new Scanner(s);
String temp = in.next();
if (temp.charAt(0) == '/')
{
temp = temp.substring(1, temp.length());
return temp;
}
return temp;
}
public String parseMessage(String s)
{
Scanner in = new Scanner(s);
String temp = in.next();
Boolean firstSpaceCheck = false;
for (int i = 0; i < temp.length(); i++)
{
if (temp.charAt(i) == ' ')
{
temp = temp.substring(i + 1, temp.length());
firstSpaceCheck = true;
}
}
return temp;
}
}
}
It's not the memory address, its the output from Object#toString which takes the format
getClass().getName() + '#' + Integer.toHexString(hashCode())
In this case it looks like [C#15b7986 which tells you you're sending the output of the character array Object back to the client so the output is that returned by Object#toString. Replace
String output = c.toString();
with
String output = new String(c);

Read a message in Server from Client RMI

I have a the necessary RMI classes created, The client can send a message and it gets printed in the server window.
On the server i would like to read the message and for example if the message is equal to 100 then print out a message.
The problem being when i run the server i immediately get a null pointer exception. When i send the message 100 from the client to the server it prints the message but wont execute the if statement.
Interface:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface FileInterface extends Remote {
void message(String message) throws RemoteException;
}
Implementation:
import java.io.*;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class FileImpl extends UnicastRemoteObject implements FileInterface {
private String name;
public FileImpl(String s) throws RemoteException {
super();
name = s;
}
public void message(String message) throws RemoteException{
System.out.println(message);
}
} catch(Exception e) {
System.err.println("FileServer exception: "+ e.getMessage());
e.printStackTrace();
return(null);
}
}
}
Client:
import java.io.*;
import java.rmi.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
public class FileClient{
public static boolean loggedIn = false;
public static void main(String argv[]) {
try {
int RMIPort;
String hostName;
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.println("Enter the RMIRegistry host namer:");
hostName = br.readLine();
if( hostName.length() == 0 ) // if user did not enter a name
hostName = "localhost"; // use the default host name
System.out.println("Enter the RMIregistry port number:");
String portNum = br.readLine();
if( portNum.length() == 0 )
portNum = "1097"; // default port number
RMIPort = Integer.parseInt(portNum);
String registryURL = "rmi://" + hostName+ ":" + portNum + "/FileServer";
// find the remote object and cast it to an interface object
FileInterface fi = (FileInterface) Naming.lookup(registryURL);
System.out.println("Lookup completed " );
//System.out.println("File " + argv[0] + " Transfered" );
// invoke the remote method
boolean done = false;
//file.getName()
while( !done ) {
System.out.println("Enter Code: 100 = Login, 200 = Upload, 300 = Download, 400 = Logout: ");
String message = br.readLine();
boolean messageOK = false;
if( message.equals("100") ) {
messageOK = true;
System.out.println("Enter T-Number: (Use Uppercase 'T')");
String login = br.readLine();
if( login.charAt(0) == 'T' ) {
loggedIn = true;
fi.message("100");
System.out.println("Login Successful");
continue;
} else {
System.out.println("Login Error");
continue;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Server:
import java.io.*;
import java.rmi.*;
public class FileServer {
public static void main(String argv[]) {
if(System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
FileInterface fi = new FileImpl("FileServer");
Naming.rebind("//localhost:1097/FileServer", fi);
System.out.println("Server Started...");
boolean done = false;
while( !done ) {
if ((msg.trim()).equals("100")) {
System.out.println("message recieved: 100 logged in");
} else {
System.out.println("Login Error");
}
}
} catch(Exception e) {
System.out.println("FileServer: "+e.getMessage());
e.printStackTrace();
}
}
}
Any help here would be appreciated.

Categories