Sockets ClassCastException HashMap - java

I've created a serverSocket and accept a client connection. However, when I try to read from the client, it is throwing the following exception. If I change HashMap to ArrayList, it does not work either.
Exception in thread "Thread-3" java.lang.ClassCastException: java.awt.Point cannot be cast to java.util.HashMap
at ServerSide.Server.getPoints(Server.java:112)
at ServerSide.Server.run(Server.java:69)
public void getPoints() throws IOException, ClassNotFoundException {
points = (HashMap<Point, Boolean>) objectInputStream.readObject();
Iterator iterator = points.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Point, Boolean> currentPoint = (Map.Entry<Point, Boolean>) iterator.next();
currentPoint.setValue(firgure.isHit(currentPoint.getKey().x, currentPoint.getKey().y));
}
objectOutputStream.writeObject(points);
}
Sending method:
#Override
public HashMap<Point, Boolean> update(HashMap<Point, Boolean> points) throws IOException {
output.println("hit");
output.flush();
toServer.writeObject(points);
try {
return (HashMap<Point, Boolean>) fromServer.readObject();
} catch (ClassNotFoundException e) {
System.out.println("Some shit with classCast!");
return null;
}
}
UDP new type exception:
java.io.StreamCorruptedException: invalid type code: 3F
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1377)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at ServerSide.Server.getPoints(Server.java:102)
at ServerSide.Server.run(Server.java:69)
This video shows how it's (not) working:
http://www.youtube.com/watch?v=8924rrSyWfY&feature=youtu.be
Maybe my server or client is bad? Can anyone see some mistake? (I so sorry for my English)
Server
public class Server extends Thread {
public static final int PORT = 1234;
private static ServerSocket serverSocket;
private Socket client;
private ObjectInputStream objectInputStream;
private ObjectOutputStream objectOutputStream;
private BufferedReader bufferedReader;
private PrintWriter printWriter;
private Firgure firgure;
private HashMap<Point, Boolean> points;
private Server(Socket client) {
System.out.println("Client connected");
this.client = client;
firgure = new Firgure();
try {
this.client.setSoTimeout(0);
} catch (SocketException e) {
e.printStackTrace();
}
setDaemon(true);
setPriority(NORM_PRIORITY);
start();
}
static public void serverStart() throws IOException {
System.out.println("Server startes");
serverSocket = new ServerSocket(PORT);
serverSocket.setSoTimeout(0);
System.out.println("Wait client");
while (true) new Server(serverSocket.accept());
}
static public void main(String[] args) throws IOException {
serverStart();
}
#Override
public void run() {
try {
objectInputStream = new ObjectInputStream(client.getInputStream());
objectOutputStream = new ObjectOutputStream(client.getOutputStream());
bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
printWriter = new PrintWriter(client.getOutputStream(), true);
points = new HashMap<Point, Boolean>();
String inputLine;
do {
inputLine = bufferedReader.readLine();
if (inputLine.equalsIgnoreCase("hit")) getPoints();
else if (inputLine.equalsIgnoreCase("echo")) echo();
else if (inputLine.equalsIgnoreCase("close")) close();
else if (inputLine.equalsIgnoreCase("set")) set();
else if (inputLine.equalsIgnoreCase("get")) get();
else continue;
} while (true);
} catch (NullPointerException e) {
System.out.println("Client disconnect");
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (java.lang.ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public int getR() {
return firgure.getR();
}
public void setR(int R) {
firgure.setR(R);
}
public void set() throws IOException, ClassNotFoundException {
setR((Integer) objectInputStream.readObject());
}
public void get() throws IOException {
objectOutputStream.writeObject(new Integer(getR()));
}
public void getPoints() throws IOException, ClassNotFoundException {
try {
points = (HashMap<Point, Boolean>) objectInputStream.readObject();
} catch (StreamCorruptedException e) {
e.printStackTrace();
points = new HashMap<Point, Boolean>();
} catch (ClassCastException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Iterator iterator = points.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Point, Boolean> currentPoint = (Map.Entry<Point, Boolean>) iterator.next();
currentPoint.setValue(firgure.isHit(currentPoint.getKey().x, currentPoint.getKey().y));
}
objectOutputStream.writeObject(points);
}
public void echo() throws IOException {
printWriter.println(bufferedReader.readLine());
}
private void close() {
try {
if (objectInputStream != null) objectInputStream.close();
if (objectOutputStream != null) objectOutputStream.close();
if (bufferedReader != null) bufferedReader.close();
if (client != null) client.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
CLient
public class Client implements IModel {
private static final int PORT = 1234;
private static final String HOST = "localhost";
private Socket server;
private ObjectOutputStream toServer;
private ObjectInputStream fromServer;
private BufferedReader input;
private PrintWriter output;
#Override
public HashMap<Point, Boolean> update(HashMap<Point, Boolean> points) throws IOException {
output.println("hit");
output.flush();
toServer.writeObject(points);
try {
return (HashMap<Point, Boolean>) fromServer.readObject();
} catch (ClassNotFoundException e) {
System.out.println("Some shit with classCast!");
return null;
}
}
#Override
public void connect() throws IOException {
server = new Socket(HOST, PORT);
toServer = new ObjectOutputStream(server.getOutputStream());
fromServer = new ObjectInputStream(server.getInputStream());
input = new BufferedReader(new InputStreamReader(server.getInputStream()));
output = new PrintWriter(server.getOutputStream(), true);
}
#Override
public void disconnect() throws IOException {
if (output != null) output.close();
if (input != null) input.close();
if (fromServer != null) fromServer.close();
if (toServer != null) toServer.close();
if (server != null) server.close();
}
#Override
public boolean isConnected() throws IOException {
if (server == null) return false;
return server.isConnected();
}
#Override
public int getFigureRadius() throws IOException {
output.println("get");
output.flush();
try {
return (Integer) fromServer.readObject();
} catch (ClassNotFoundException e) {
System.out.println("Some shit with cast");
return 0;
}
}
#Override
public void setFigureRadius(int newRadius) throws IOException {
output.println("set");
output.flush();
toServer.writeObject(newRadius);
}
}

This is very clear from your exception message. You are sending a Point and trying to receive a HashMap.

From log you get error on casting:
points = (HashMap<Point, Boolean>) objectInputStream.readObject();
To debug try:
Object obj = objectInputStream.readObject();
if(obj instanceof Map<Point, Boolean>){
...
}
else if(obj instanceof String){
...
}

Related

Java how to read with ObjectInputStream

It's my first time working with sockets, in order to get a better understanding of what's going on I decided to build a client server chat application which can support several users.
At first, I used DataInputStream / DataOutputStream to communicate and everything works well. But I would like to switch to an ObjectStream and that's where the problem occurs. Once I replace all the DataInputStream / DataOutputStream by ObjectInputStream / ObjectOutputStream, I'm no longer able to print the retrieved data.
This is the code that I used before, which works (DataStream) :
SERVER:
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("HI FROM SERVER");
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
String input = in.readUTF();
for (ClientThread thatClient : server.getClients()){
DataOutputStream outputParticularClient = new DataOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeUTF(input + " GOT FROM SERVER");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket("localhost", portNumber);
DataInputStream in = new DataInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
String input = in.readUTF();
System.out.println(getUserName() + " > " + input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
And this is how I tried to perform the same idea with ObjectStream :
SERVER:
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
Message input;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("SERVER RETRIEVED NULL OBJECT");
}
for (ClientThread thatClient : server.getClients()){
ObjectOutputStream outputParticularClient = new ObjectOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeObject(input);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket(getHost(), portNumber);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
Message input = null;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("CLIENT RETRIEVED NULL OBJECT");
}
System.out.println("CLIENT " + input.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
I feel like it has something to do with this if statement if (in.available() > 0) but I cannot say precisely what's going on.
available() doesn't do what you may think it does and it is almost never useful in production code (and that's particularly true for ObjectInputStream). The reason you don't receive any data is in fact that in.available() always returns 0 as you already suspected.
As noted in the comments, the StreamCorruptedException is caused by writing to an existing ObjectInputStream that has already been written to using another instance of ObjectOutputStream. Cf. the answer StreamCorruptedException: invalid type code: AC for further explanation.
Here is some quick & dirty example code that has a server echoing the messages from two clients. It's not clean but it may give you an idea how to approach your problem:
public class SO56493162 {
private static final class Message implements Serializable {
private static final long serialVersionUID = 1L;
private static int cnt = 0;
private final int id;
public Message(int id) {
++cnt;
this.id = id;
}
public String toString() {
return "Msg from " + id + " : " + cnt;
}
}
private static final class Client implements Runnable {
private InetSocketAddress addr = null;
private int id = -1;
Client(InetSocketAddress addr, int id) {
this.addr = addr;
this.id = id;
}
public void run() {
int timeout = 3000;
Socket s = null;
try {
s = new Socket();
s.connect(addr, timeout);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println("Client " + id + " connected");
while (true) {
Thread.sleep(new Random().nextInt(2000));
Message hello = new Message(id);
oos.writeObject(hello);
oos.flush();
Message reply = (Message) ois.readObject();
System.out.println("Reply: " + reply.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (Exception ignore) {
}
}
}
}
private static final class Server implements Runnable {
private ServerSocket sock = null;
Server(ServerSocket sock) throws IOException {
this.sock = sock;
}
public void run() {
System.out.println("starting server");
try {
while (true) {
final Socket client = sock.accept();
System.out.println("connection accepted");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
while (!client.isClosed()) {
try {
Message input = (Message) ois.readObject();
oos.writeObject(input);
oos.flush();
} catch (EOFException eof) {
System.err.println("EOF!");
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException, InterruptedException {
final int port = 9876;
Thread ts = new Thread(new Runnable() {
#Override
public void run() {
try {
new Server(new ServerSocket(port)).run();
} catch (Exception e) {
e.printStackTrace();
}
}
});
ts.setDaemon(true);
ts.start();
InetSocketAddress addr = new InetSocketAddress("localhost", port);
for (int i = 0; i < 2; ++i) {
Client cl = new Client(addr, i);
Thread tc = new Thread(cl);
tc.setDaemon(true);
tc.start();
}
Thread.sleep(10000);
System.err.println("done");
}
}

Java multi client game server

I am having trouble making a multi client server for a game that i have made. I am able to create a ServerSocket, make a connection and send data through means of a ObjectInputStream and ObjectOutputStream. My problems lies when it comes to multiple clients, from what i understand a new thread needs to be created for each client but the data i would like to send and receive is hard coded into the client class. How would I allow my Client to send changeable data?
Here is my client class:
public class Client extends Thread {
private Server server = new Server();
private Socket connection;
private ObjectOutputStream out;
private ObjectInputStream in;
public Client(Socket connection) {
this.connection = connection;
this.out = server.objOutStream(this.connection);
this.in = server.objInStream(this.connection);
}
public void run() {
while(this.connection.isConnected()) {
//
List<String> list = new ArrayList<String>();
list.add("hello there");
server.sendData(out, list);
//
List<String> recive = new ArrayList<String>();
recive = server.reveiveData(in);
}
}
public Socket getConnection() {
return connection;
}
}
and Here is the server side:
public ServerSocket createServer(Integer serverPort, Integer serverSize) {
ServerSocket server = null;
try {
server = new ServerSocket(serverPort, serverSize);
System.out.println("created server");
} catch (IOException e) {
e.printStackTrace();
}
return server;
}
public Socket makeConnection(ServerSocket server) {
Socket connection = null;
try {
connection = server.accept();
Client client = new Client(connection);
client.start();
System.out.println("connection made with " + connection.getInetAddress().getHostAddress());
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
public ObjectInputStream objInStream(Socket connection) {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return in;
}
public ObjectOutputStream objOutStream(Socket connection) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(connection.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
public void sendData(ObjectOutputStream out, List<String> list) {
try {
out.writeObject(list);
out.flush();
System.out.println("sending " + list);
} catch (IOException e) {
e.printStackTrace();
}
}
public List<String> reveiveData(ObjectInputStream in) {
List<String> list = null;
try {
list = (List<String>) in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return list;
}
public Socket joinServer(String serverIP, Integer serverPort) {
Socket connection = null;
try {
connection = new Socket(InetAddress.getByName(serverIP), serverPort); System.out.println("joined");
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
public void stop(Socket connection) {
System.out.println("closing");
try {
if(connection.isInputShutdown() == false) {
connection.getInputStream().close();
}
if(connection.isOutputShutdown() == false) {
connection.getOutputStream().close();
}
if(connection.isConnected() == true) {
connection.close();
}
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
In my mian class I run this:
try {
if(connection == null) {
connection = server.makeConnection(serverSocket);
in = server.objInStream(connection);
out = server.objOutStream(connection);
}else {
//readlist
List<String> readList = (List<String>) in.readObject();
System.out.println("reciving: " + readList);
//writelist
List<String> writeList = new ArrayList<String>();
writeList.add("hi");
out.writeObject(writeList);
System.out.println("sending: " + writeList);
}
}catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}

Java - Change Object Attribute From Other Thread

I am writing simple client-server program. The problem, that I have faced is following: I am sending an object from client to server and I start new thread for every object sent to server.
I need to get data from deserialized object and update server object attribute with this data. How can I do that?
This is my server code:
...
// Property to be updated
private FieldMap fieldMap = new FieldMap();
public void startServer() {
try {
serverSocket.bind(new InetSocketAddress("localhost", port));
(new Thread(this)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopServer() {
running = false;
Thread.currentThread().interrupt();
}
#Override
public void run() {
running = true;
while (running) {
try {
this.setChanged();
this.notifyObservers();
System.out.println("Listening for a connection");
Socket socket = serverSocket.accept();
InputHandler inputHandler = new InputHandler(socket, fieldMap);
(new Thread(inputHandler)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
...
This is listener object code:
public class InputHandler implements Runnable {
private Socket socket;
private ObjectInputStream objectInputStream;
private FieldMap map;
InputHandler(Socket socket, FieldMap map) throws IOException {
this.socket = socket;
objectInputStream = new ObjectInputStream(socket.getInputStream());
this.map = map;
}
#Override
public void run() {
try {
Lemming lemming = (Lemming) objectInputStream.readObject();
lemming.getFieldMap().union(map);
map = lemming.getFieldMap();
System.out.println(lemming);
(new Thread(lemming)).start();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
objectInputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
How to update fieldMap from InputHandler?
You need some methods like in java.uitl.Map
fieldMap.clear()
fieldMap.putAll(otherFieldMap)

Java Sockets sending multiple objects to the same server

I'm trying to send multiple Objects through a socket to a java server.
To have a gerneral type I convert my messages into an instance of the class Message and send this object to the server.
I wrote a little testclass, which sends three objects to the server.
The problem is, only one objects reaches the server.
I tried nearly everything, without success.
My Server:
public class Server {
private ServerConfig conf = new ServerConfig();
private int port = Integer.parseInt(conf.loadProp("ServerPort"));
Logger log = new Logger();
ServerSocket socket;
Chat chat = new Chat();
public static void main(String[] args) {
Server s = new Server();
if (s.runServer()) {
s.listenToClients();
}
}
public boolean runServer() {
try {
socket = new ServerSocket(port);
logToConsole("Server wurde gestartet!");
return true;
} catch (IOException e) {
logToConsole("Server konnte nicht gestartet werden!");
e.printStackTrace();
return false;
}
}
public void listenToClients() {
while (true) {
try {
Socket client = socket.accept();
ObjectOutputStream writer = new ObjectOutputStream(client.getOutputStream());
Thread clientThread = new Thread(new Handler(client, writer));
clientThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void logToConsole(String message) {
System.out.print(message);
}
public class Handler implements Runnable {
Socket client;
ObjectInputStream reader;
ObjectOutputStream writer;
User user;
public Handler(Socket client, ObjectOutputStream writer) {
try {
this.client = client;
this.writer = writer;
this.reader = new ObjectInputStream(client.getInputStream());
this.user = new User();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
Message incomming;
try {
while ((incomming = (Message) reader.readUnshared()) != null) {
logToConsole("Vom Client: \n" + reader.readObject().toString() + "\n");
logToConsole(
"Vom Client: \n" + incomming.getType() + "-----" + incomming.getValue().toString());
handle(incomming);
}
} catch (SocketException se) {
se.printStackTrace();
Thread.currentThread().interrupt();
} catch (IOException ioe) {
ioe.printStackTrace();
Thread.currentThread().interrupt();
} catch (ClassNotFoundException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
private void handle(Message m) throws IOException {
String type = m.getType();
if (type.equals(config.ConstantList.Network.CHAT.toString())) {
chat.sendMessage(m);
} else if (type.equals(config.ConstantList.Network.LOGIN.toString())) {
System.out.println(user.login(m.getValue().get(0), writer));
System.out.println(m.getValue().get(0));
}
}
}
}
The Client:
public class Connect {
Socket client = null;
ObjectOutputStream writer = null;
ObjectInputStream reader = null;
private Config conf = new Config();
//private String host = conf.loadProp("ServerIP");
String host = "localhost";
private int port = Integer.parseInt(conf.loadProp("ServerPort"));
public boolean connectToServer() {
try {
client = new Socket(host, port);
reader = new ObjectInputStream(client.getInputStream());
writer = new ObjectOutputStream(client.getOutputStream());
logMessages("Netzwerkverbindung hergestellt");
Thread t = new Thread(new MessagesFromServerListener());
t.start();
return true;
} catch (Exception e) {
logMessages("Netzwerkverbindung konnte nicht hergestellt werden");
e.printStackTrace();
return false;
}
}
public boolean isConnectionActive() {
if (client == null || writer == null || reader == null){
return false;
}else{
return true;
}
}
public void sendToServer(Message m) {
try {
writer.reset();
writer.writeUnshared(m);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
And I try to send the objects with the class:
public void sendChatMessage(String username, String message) throws InterruptedException {
ChatMessage cm = new ChatMessage();
cm.setChat(username, null, message);
Message m = new Message(cm);
conn.sendToServer(m);
System.out.println("SENDED");
}
public static void main(String[] args) throws InterruptedException {
String username = "testuser";
String chatmessage = "Hallo Welt!";
connect.connect();
sendChatMessage(username, chatmessage);
sendChatMessage(username, chatmessage);
sendChatMessage(username, chatmessage);
}
I know that this is always the same message, but it is only for test purposes.
The messages are the objects they are Serializable and with only one object it works as designed.
Does anyone can see where I made my mistake?
while ((incomming = (Message) reader.readUnshared()) != null) {
Here you are reading an object, and blocking until it arrives.
logToConsole("Vom Client: \n" + reader.readObject().toString() + "\n");
Here you are reading another object, and blocking till it arrives, and then erroneously logging it as the object you already read in the previous line.
Instead of logging reader.readObject(), you should be logging the value of incoming, which you have also misspelt.
And the loop is incorrect. readObject() doesn't return null at end of stream: it throws EOFException. It can return null any time you write null, so using it as a loop termination condition is completely wrong. You should catch EOFException and break.
Found the solution, the line logToConsole("Vom Client: \n" + reader.readObject().toString() + "\n"); in the Server class, blocks the connection.

How to stop all instances of a thread

I'm developping a socket-based game in Java about riddles in a competitive way.
The server program creates a response thread besides other threads for each player (client), what I want to do is stop (or interrupt) all those response threads once a player sends the right response.
Here's my code
public class testReponse implements Runnable {
private Socket socket;
BufferedReader in;
PrintWriter out;
String reponse="";
public testReponse(Socket socket2){
socket = socket2;
}
#Override
public void run() {
while(!reponse.equals("right")){
try {
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String reponse = in.readLine();
System.out.println("Reponse : "+ reponse);
if(reponse.equals("right")){
out.println("correct");
out.flush();
} else {
out.println("incorrect");
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is not clear where is your server code is. However, the way I would do it is by having an AtomicBoolean as an instance variable in the server code. Once the "right" message is received from any of the clients, the value would change to false. In the code in the server side if you see that the value is false, then you stop!
This is one way to go about it but there might be better ways to do it though.
public class MyServer {
private AtomicBoolean keepServerOn = new AtomicBoolean(true);
public void setKeepServerOff() {
keepServerOn.set(false);
}
public void shouldKeepGoing() {
return keepServerOn.get();
}
public static void main(Strings[] args) {
....// where you accept clients and create TestResponse
MyServer myServer = new MyServer();
...// somewhere new TestResponse(socket, myServer);
}
}
public class testReponse implements Runnable {
private MyServer server;
private Socket socket;
private AtomicBoolean keepServerOn = new AtomicBoolean(true);
public testReponse(Socket socket2, MyServer server){
socket = socket2;
}
#Override
public void run() {
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
while(server.shouldKeepGoing()){
String reponse = in.readLine();
System.out.println("Reponse : "+ reponse);
if(reponse.equals("right")){
server.setKeepServerOff();
out.println("correct");
out.flush();
} else {
out.println("incorrect");
out.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!= null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Categories

Resources