Message not being sent when Akka actor is killed using DeathWatch - java

I'm attempting to send a message when an actor is killed.
This is based on Akka deathwatch documentation :
http://doc.akka.io/docs/akka/2.3.6/java/untyped-actors.html#deathwatch-java
In serviceActor I'm awaiting a "kill" message but I'm never actually sending this message. So to receive the message in ServiceActor I use :
else if (msg instanceof Terminated) {
final Terminated t = (Terminated) msg;
if (t.getActor() == child) {
lastSender.tell(Msg.TERMINATED, getSelf());
}
} else {
unhandled(msg);
}
I've set the duration to 10 milliseconds :
Duration.create(10, TimeUnit.MILLISECONDS)
But the message Msg.TERMINATED is never received in onReceive method :
#Override
public void onReceive(Object msg) {
if (msg == ServiceActor.Msg.SUCCESS) {
System.out.println("Success");
getContext().stop(getSelf());
} else if (msg == ServiceActor.Msg.TERMINATED) {
System.out.println("Terminated");
} else
unhandled(msg);
}
How can I send a message to HelloWorld when ServiceActor fails ?
Entire code :
package terminatetest;
import akka.Main;
public class Launcher {
public static void main(String args[]) {
String[] akkaArgsArray = new String[1];
akkaArgsArray[0] = "terminatetest.HelloWorld";
Main.main(akkaArgsArray);
}
}
package terminatetest;
import java.util.concurrent.TimeUnit;
import scala.concurrent.duration.Duration;
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.actor.Props;
import akka.actor.UntypedActor;
public class HelloWorld extends UntypedActor {
#Override
public void preStart() {
int counter = 0;
akka.actor.ActorSystem system = getContext().system();
final ActorRef greeter = getContext().actorOf(
Props.create(ServiceActor.class), String.valueOf(counter));
system.scheduler().scheduleOnce(
Duration.create(10, TimeUnit.MILLISECONDS), new Runnable() {
public void run() {
greeter.tell(PoisonPill.getInstance(), getSelf());
}
}, system.dispatcher());
greeter.tell("http://www.google.com", getSelf());
counter = counter + 1;
}
#Override
public void onReceive(Object msg) {
if (msg == ServiceActor.Msg.SUCCESS) {
System.out.println("Success");
getContext().stop(getSelf());
} else if (msg == ServiceActor.Msg.TERMINATED) {
System.out.println("Terminated");
} else
unhandled(msg);
}
}
package terminatetest;
import static com.utils.PrintUtils.println;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.Terminated;
import akka.actor.UntypedActor;
public class ServiceActor extends UntypedActor {
final ActorRef child = this.getContext().actorOf(Props.empty(), "child");
{
this.getContext().watch(child);
}
ActorRef lastSender = getContext().system().deadLetters();
public static enum Msg {
SUCCESS, FAIL, TERMINATED;
}
#Override
public void onReceive(Object msg) {
if (msg instanceof String) {
String urlName = (String) msg;
try {
long startTime = System.currentTimeMillis();
URL url = new URL(urlName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println("Connection successful to " + url);
System.out.println("Content is " + out);
long endTime = System.currentTimeMillis();
System.out.println("Total Time : " + (endTime - startTime) + " milliseconds");
} catch (MalformedURLException mue) {
println("URL Name " + urlName);
System.out.println("MalformedURLException");
System.out.println(mue.getMessage());
mue.printStackTrace();
getSender().tell(Msg.FAIL, getSelf());
} catch (IOException ioe) {
println("URL Name " + urlName);
System.out.println("IOException");
System.out.println(ioe.getMessage());
ioe.printStackTrace();
System.out.println("Now exiting");
getSender().tell(Msg.FAIL, getSelf());
}
}
else if (msg instanceof Terminated) {
final Terminated t = (Terminated) msg;
if (t.getActor() == child) {
lastSender.tell(Msg.TERMINATED, getSelf());
}
} else {
unhandled(msg);
}
}
}
Update :
I'm now initiating the poisonPill from the child actor itself using :
Update to ServiceActor :
if (urlName.equalsIgnoreCase("poisonPill")) {
this.getSelf().tell(PoisonPill.getInstance(), getSelf());
getSender().tell(Msg.TERMINATED, getSelf());
}
Update to HelloWorld :
system.scheduler().scheduleOnce(
Duration.create(10, TimeUnit.MILLISECONDS), new Runnable() {
public void run() {
greeter.tell("poisonPill", getSelf());
}
}, system.dispatcher());
This displays following output :
startTime : 1412777375414
Connection successful to http://www.google.com
Content is ....... (I'veremoved the content for brevity)
Total Time : 1268 milliseconds
Terminated
The poisonPill message is sent after 10 milliseconds and for this example the actor lives for 1268 milliseconds. So why is the actor not terminating when the poisonPill is sent ? Is this because the timings are so short ?
Updated code :
package terminatetest;
import java.util.concurrent.TimeUnit;
import scala.concurrent.duration.Duration;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
public class HelloWorld extends UntypedActor {
#Override
public void preStart() {
int counter = 0;
akka.actor.ActorSystem system = getContext().system();
final ActorRef greeter = getContext().actorOf(
Props.create(ServiceActor.class), String.valueOf(counter));
system.scheduler().scheduleOnce(
Duration.create(10, TimeUnit.MILLISECONDS), new Runnable() {
public void run() {
greeter.tell("poisonPill", getSelf());
}
}, system.dispatcher());
greeter.tell("http://www.google.com", getSelf());
counter = counter + 1;
}
#Override
public void onReceive(Object msg) {
if (msg == ServiceActor.Msg.SUCCESS) {
System.out.println("Success");
getContext().stop(getSelf());
} else if (msg == ServiceActor.Msg.TERMINATED) {
System.out.println("Terminated");
} else
unhandled(msg);
}
}
package terminatetest;
import static com.utils.PrintUtils.println;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.actor.UntypedActor;
public class ServiceActor extends UntypedActor {
ActorRef lastSender = getSender();
public static enum Msg {
SUCCESS, FAIL, TERMINATED;
}
#Override
public void onReceive(Object msg) {
if (msg instanceof String) {
String urlName = (String) msg;
if (urlName.equalsIgnoreCase("poisonPill")) {
this.getSelf().tell(PoisonPill.getInstance(), getSelf());
getSender().tell(Msg.TERMINATED, getSelf());
}
else {
try {
long startTime = System.currentTimeMillis();
System.out.println("startTime : "+startTime);
URL url = new URL(urlName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println("Connection successful to " + url);
System.out.println("Content is " + out);
long endTime = System.currentTimeMillis();
System.out.println("Total Time : " + (endTime - startTime) + " milliseconds");
} catch (MalformedURLException mue) {
println("URL Name " + urlName);
System.out.println("MalformedURLException");
System.out.println(mue.getMessage());
mue.printStackTrace();
getSender().tell(Msg.FAIL, getSelf());
} catch (IOException ioe) {
println("URL Name " + urlName);
System.out.println("IOException");
System.out.println(ioe.getMessage());
ioe.printStackTrace();
System.out.println("Now exiting");
getSender().tell(Msg.FAIL, getSelf());
}
}
}
}
}

I think your problem stems from the fact that you only set lastSender once, during construction of the ServiceActor, and you explicitly set it to deadletter. If you want to send a message back to the actor that sent you the String message, then you will need to set lastSender to that sender(). Failure to do so will result in your Msg.TERMINATED always going to deadletter.
EDIT
I see the real issue here now. In the HelloWorld actor, you are sending a PoisonPill to the ServiceActor. The ServiceActor will stop itself as a result, thus stopping the child ref too (as it's a child actor to ServiceActor). At this point, you would think the Terminated message would be delivered to ServiceActor because it explicitly watches child (and it probably does get delivered), but you've already sent a PoisonPill to ServiceActor so it will not process any messages received after that message (which would be the Terminate) so that's why the block:
else if (msg instanceof Terminated) {
is never hit in ServiceActor.
EDIT2
Your actor receives the request to hit google first and receives the "poisonPill" message second (10 milliseconds later). As an actor processes it's mailbox in order, the actor fully processes the request to hit google before it processes the message to stop itself. That's why the actor doesn't stop after 10 milliseconds. You can't stop an actor in the middle of what it's doing.

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.

Custom Java Socket class

This is my first time messing around with Sockets, and it was working up until now. Basically, I have a custom ServerSocket class named Server and a custom Socket class named Client.
When Client tries to connect to Server, Server performs a little check to make sure it is actually Client that it trying to make the connection, and not some other socket, because Client has certain methods that I need.
However, this check always returns false. Here is my Server connection code:
package me.eli.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import me.eli.client.Client;
public class Server extends ServerSocket {
private final Map<Client, IOPair> clients = new HashMap<Client, IOPair>();
public Server(final int port) throws IOException {
super(port);
System.out.println("Server started on " + getLocalPort() + "... Waiting for client!");
}
public Client waitOnClient() throws IOException {
final Socket generalClient = accept();
final Client client;
if(!(generalClient instanceof Client)) {
client = null;
PrintWriter out = new PrintWriter(generalClient.getOutputStream(), true);
out.println("Access denied: " + generalClient.getClass().getSimpleName());
log("Invalid client: " + generalClient.getClass().getName() + " (" + generalClient.getInetAddress().getHostAddress() + ")");
out.close();
} else
client = (Client) generalClient;
if(client == null)
return null;
client.setServer(this);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
broadcast(client.getName() + " has joined.");
clients.put(client, new IOPair(in, out));
System.out.println("Client (" + client.getName() + ") connected from " + client.getInetAddress().getHostAddress());
out.println("Connected! Welcome to the server.");
return client;
}
#Override
public void close() throws IOException {
for(Client c : getClients())
kick(c, "Server closed");
super.close();
}
public void kick(Client c, String reason) {
try {
c.message("disconnect", reason);
c.close();
} catch(IOException e) {
log("Failed to kick " + c.getName() + ": " + e.getMessage());
c.message("error", "Failed to disconnect");
}
}
public void log(String message) {
getServerOut().println(message);
}
public void log(String source, String message) {
log("<" + source + "> " + message);
}
public void broadcast(String message) {
log("broadcast", message);
for(Client c : getClients())
c.message("broadcast", message);
}
public Client[] getClients() {
return clients.keySet().toArray(new Client[clients.keySet().size()]);
}
public BufferedReader getClientIn(Client c) {
return clients.get(c).getIn();
}
public PrintWriter getClientOut(Client c) {
return clients.get(c).getOut();
}
public InputStream getServerIn() {
return System.in;
}
public PrintStream getServerOut() {
return System.out;
}
public static boolean isServerRunningOn(final int port) {
try {
new ServerSocket(port).close();
return false;
} catch(IOException e) {
return true;
}
}
}
And here is my Client connection code:
package me.eli.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import me.eli.server.IOPair;
import me.eli.server.Server;
public class Client extends Socket {
private Server server;
private final IOPair serverio;
private final String name;
public Client(final String host, final int port) throws IOException {
this(host, port, "Guest-" + (int) (Math.random() * 10000));
}
public Client(final String host, final int port, final String name) throws IOException {
super(host, port);
System.out.println("Connected to server on " + host + ":" + port);
BufferedReader in = new BufferedReader(new InputStreamReader(getInputStream()));
PrintWriter out = new PrintWriter(getOutputStream(), true);
this.name = name;
this.serverio = new IOPair(in, out);
String input;
if((input = in.readLine()) != null)
System.out.println("<Welcome message> " + input);
out.println("Yay! I'm connected!");
}
#Override
public synchronized void close() throws IOException {
if(serverio != null) {
if(server != null)
server.broadcast(getName() + " has disconnected.");
message("server", "Disconnected.");
super.close();
serverio.getIn().close();
serverio.getOut().close();
} else
super.close();
}
public void message(String source, String message) {
getClientOut().println("<" + source + "> " + message);
}
public String getName() {
return name;
}
public void setServer(Server server) {
this.server = server;
}
public Server getServer() {
return server;
}
public BufferedReader getServerIn() {
return serverio.getIn();
}
public PrintWriter getServerOut() {
return serverio.getOut();
}
public InputStream getClientIn() {
return System.in;
}
public PrintStream getClientOut() {
return System.out;
}
}
I'm not the most experienced with networking, but this confuses me because I do indeed connect with my Client class. Thanks in advance!
Server performs a little check to make sure it is actually Client that it trying to make the connection
Impossible and nonsensical. The Client class is at the other end of the connection. It is not magically transmitted to your accept() method. If you want to validate your client you will have to build something into your application protocol.
Notes:
Calling Client.setServer() is similarly futile. It is not magically transmitted to the client.
It is possible to get your ServerSocket-derived class to create Client objects instead of Socket objects in its accept() method, but that doesn't actually solve the issue you're trying to solve.

Persistent connection not working, opens new connection on every request

I am trying to implement a persistent http server in java, being new in socket programming, I am unaware of the complications.
But run function of ThreadHandler class, it stucks forever and keep waiting, but at the same time if new request comes a new connection is being made instead of using the previous connection itself (while the initial connection keep waiting for request).
Please suggest the correction
here is my server code that calls ThreadHandler for threading.
Server code
package httpServer;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class Server {
static int countofconnections = 0;
public static void main(String[] args) throws IOException {
int port = 14998;
ServerSocket socketServerSocket = new ServerSocket(port);
while(true) {
Socket socketClientSocket = socketServerSocket.accept();
countofconnections++;
//Runnable handler = new TinyHttpdSocketHandler(socket);
ThreadHandler threadHandler = new ThreadHandler(socketClientSocket);
Thread socketThread = new Thread(threadHandler, "Thread for " + socketClientSocket.toString());
System.out.println(" connection count is now : " + countofconnections+ " ");
socketThread.setDaemon(true);
socketThread.start();
}
}
}
ThreadHandler code:
package httpServer;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketTimeoutException;
//import java.util.ArrayList;
public class ThreadHandler implements Runnable{
Socket socketClientSocket;
//ServerSocket socketServerSocket;
ThreadHandler(Socket socketClientSocket){
this.socketClientSocket = socketClientSocket;
//this.socketServerSocket = socketServerSocket;
}
#Override
public void run(){
boolean alive = false;
try {
int count = 0;
socketClientSocket.setSoTimeout(40000);
BufferedReader inputFromClient = new BufferedReader(new InputStreamReader(socketClientSocket.getInputStream()));
DataOutputStream outputToClient = new DataOutputStream(socketClientSocket.getOutputStream());
String messegeFromClient = inputFromClient.readLine();
System.out.println(messegeFromClient);
while(messegeFromClient!=null) {
String requestString = messegeFromClient;
System.out.println("entering while loop");
//String in = inputFromClient.readLine();
while(messegeFromClient!=null && !messegeFromClient.equals("")) {
//System.out.printlnln(in);
messegeFromClient = inputFromClient.readLine();
//System.out.println(messegeFromClient);
if(messegeFromClient.startsWith("Connection:")) {
String[] connectionTimeString = messegeFromClient.split(" ");
if(connectionTimeString[1].equals("keep-alive")) {
alive = true;
//System.out.println("keep alive found");
}
}
}
count++;
System.out.println(count);
//System.out.printlnln( messegeFromClient);
String[] tokensStrings = requestString.split(" ");
if(tokensStrings[0].equals("GET")) {
String requestedFilename = tokensStrings[1];
if(requestedFilename.startsWith("/")) {
requestedFilename = requestedFilename.substring(1);
if(requestedFilename.startsWith("~")) {
requestedFilename = "/home/suman/users/"+requestedFilename.substring(1);
}
else {
requestedFilename = "/home/suman/public_html/"+requestedFilename;
}
System.out.println(requestedFilename);
}
File filetosend = new File(requestedFilename);
int filesize = (int) filetosend.length();
FileInputStream fileStream = null;
boolean fileFound = true;
try {
fileStream = new FileInputStream(requestedFilename);
} catch (Exception e) {
fileFound = false;
}
if(fileFound) {
byte[] fileinByte =new byte[filesize];
fileStream.read(fileinByte);
outputToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");
outputToClient.writeBytes("Content-Length: "+filesize+"\r\n\r\n");
outputToClient.write(fileinByte, 0, filesize);
}
else {
outputToClient.writeBytes("HTTP/1.0 404 Document NOT FOUND\r\n\r\n");
outputToClient.writeBytes("404 document not found");
}
outputToClient.flush();
if(alive) {
socketClientSocket.setKeepAlive(true);
socketClientSocket.setSoTimeout(100000);
}
else {
socketClientSocket.close();
System.out.println("closing socket");
break;
}
//socketClientSocket.setSoTimeout(5000);
}
System.out.println("waiting");
messegeFromClient=inputFromClient.readLine();
while( messegeFromClient == null ) {
//this code should be skipped when a new request is made since message from from client will no longer be null in that case
messegeFromClient=inputFromClient.readLine();
}
if(messegeFromClient==null) {
System.out.println("messege is null... I don't think it would be ever executed.");
}
}
socketClientSocket.close();
System.out.println("closing socket 2");
} catch ( SocketTimeoutException e) {
try {
socketClientSocket.close();
System.out.println("socket closed");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException ie) {
ie.printStackTrace();
}
}
}

Sockets - SocketException: Socket Closed - Java

I've been playing around with sockets recently, but I've come across a problem...
I'm getting a "java.net.SocketException: socket closed" exception when I receive data from the server. I haven't closed the socket anywhere, in fact, the only place I use close() is on the scanner to read text from System.in;
Here is my code:
Client:
package packets.sidedcomputer;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import packets.MessagePacket;
import packets.sender.PacketSender;
import packets.side.Side;
public class Client extends SidedComputer
{
volatile boolean finished = false;
volatile String username;
volatile Server server;
public Socket clientSocket;
public ClientReciever reciever;
public Client(Server server, String username) throws UnknownHostException, IOException
{
this.username = username;
this.server = server;
this.reciever = new ClientReciever(this);
}
public void stopClient()
{
finished = true;
}
#Override
public void run()
{
Scanner scanner = new Scanner(System.in);
reciever.start();
while(!finished)
{
try
{
this.clientSocket = new Socket("192.168.1.25", 10501);
String line;
while((line = scanner.nextLine()) != null)
{
PacketSender sender = new PacketSender();
System.out.println("Client sending message \"" + line + "\" to server");
sender.sendPacket(new MessagePacket(line, username), clientSocket);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
scanner.close();
}
#Override
public Side getSide()
{
return Side.CLIENT;
}
}
Server:
package packets.sidedcomputer;
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.List;
import packets.Packet;
import packets.data.PacketData;
import packets.info.ClientInfo;
import packets.reciever.PacketReciever;
import packets.sender.PacketSender;
import packets.side.Side;
public class Server extends SidedComputer
{
volatile boolean finished = false;
public ServerSocket serverSocket;
public volatile List<ClientInfo> clients = new ArrayList<ClientInfo>();
public void stopServer()
{
finished = true;
}
public Server()
{
try
{
serverSocket = new ServerSocket(10501);
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void run()
{
try
{
while (!finished)
{
Socket clientSocket = serverSocket.accept();
if(clientSocket != null)
{
ClientInfo clientInfo = new ClientInfo(clientSocket);
this.clients.add(clientInfo);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String dataString;
while((dataString = in.readLine()) != null)
{
PacketReciever packetReciever = new PacketReciever();
PacketData packetData = new PacketData();
packetData.decodeInto(dataString);
Packet packet = packetReciever.recievePacket(packetData, packetData.packetID, getSide(), clientSocket.getLocalAddress().getHostAddress().toString(), clientSocket.getLocalPort() + "");
PacketSender packetSender = new PacketSender();
for (ClientInfo client : this.clients)
{
PrintWriter out = new PrintWriter(client.socket.getOutputStream(), true);
packetSender.sendPacketToClient(packet, out);
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
#Override
public Side getSide()
{
return Side.SERVER;
}
}
Packet Sender:
package packets.sender;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import packets.Packet;
import packets.data.PacketData;
public class PacketSender implements IPacketSender
{
#Override
public void sendPacket(Packet packet, Socket socket)
{
if(packet.getDefualtID() == 0)
{
PacketData packetData = new PacketData(packet.getDefualtID());
packet.writeData(packetData);
String data = packetData.encodeIntoString();
sendData(socket, data);
}
}
protected void sendData(Socket socket, String data)
{
try
{
try
(
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
)
{
out.println(data);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to " + socket);
System.exit(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void sendPacketToClient(Packet packet, PrintWriter out)
{
PacketData packetData = new PacketData(packet.getDefualtID());
packet.writeData(packetData);
String data = packetData.encodeIntoString();
out.println(data);
}
}
Client Receiver:
package packets.sidedcomputer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import packets.data.PacketData;
import packets.reciever.PacketReciever;
import packets.side.Side;
public class ClientReciever extends Thread
{
public Client client;
public ClientReciever(Client client)
{
this.client = client;
}
volatile boolean running = true;
public void stopRunning()
{
running = false;
}
#Override
public void run()
{
while(running)
{
if(client.clientSocket != null)
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(client.clientSocket.getInputStream()));
String line;
while((line = in.readLine()) != null)
{
PacketReciever reciever = new PacketReciever();
PacketData packetData = new PacketData();
packetData.decodeInto(line);
reciever.recievePacket(packetData, packetData.packetID, Side.CLIENT, client.clientSocket.getLocalAddress().getHostAddress().toString(), client.clientSocket.getPort() + "");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
Packet Receiver:
package packets.reciever;
import packets.Packet;
import packets.MessagePacket;
import packets.data.PacketData;
import packets.side.Side;
public class PacketReciever implements IPacketReciever
{
#Override
public Packet recievePacket(PacketData packetData, int id, Side side, String hostName, String port)
{
Packet packet = null;
if(id == 0)
{
packet = new MessagePacket();
packet.readData(packetData);
packet.execute(side, hostName + ":" + port);
}
return packet;
}
}
I think the problem is your try-with-resources call in the sender, which will call close() at the end of the try block and hence close the Socket. Try using a single PrintWriter across all calls to sendData().

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