Java Sockets sending multiple objects to the same server - java

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.

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");
}
}

Android client/server application - proper way to receive messages continously

I'm trying to make a client/server application using an Android phone as a client using AsyncTask to send messages from UI.
I've written some very basic implementation just to test the connection and the way that messages are received / sent and I found a very big problem.
The client part seems to work fine..from my perspective. But the server part is the problem. I can't make the server reading and displaying messages countinously from the client.
I tried something like while(line = (in.readLine()) != null) {} but it doesn't seems to work.
After I sent my first word from the client, the server reads null and it stops.
Can someone show me a proper way to keep the server running while the client is not sending nothing?
I'd like to avoid using while(true) if it's not 100% necessary.
Here is the implementation until now:
Server:
public class SocketServerThread extends Thread {
private static final Logger log = Logger.getLogger(SocketServerThread.class);
private static final int SERVER_PORT_NUMBER = 5000;
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT_NUMBER);
serverSocket.setReuseAddress(true);
log.info("Waiting for connection...");
Socket clientSocket = serverSocket.accept();
log.info("Connected! Receiving message...");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
try {
while (true) {
String line = in.readLine();
if (line != null) {
log.info(line);
}
}
} catch (Exception e) {
log.error("Unexpected exception while sending / receiving messages.");
e.printStackTrace();
} finally {
in.close();
clientSocket.close();
serverSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Client:
public class MyAsyncTask extends AsyncTask<String, Integer, String> {
private static final String TAG = "MyAsyncTask";
private static final String SERVER_IP_ADDRESS = "10.0.2.2";
private static final int SERVER_PORT_NUMBER = 5000;
private PrintWriter out;
#Override
protected String doInBackground(String... params) {
String message = "";
try {
InetAddress address = InetAddress.getByName(SERVER_IP_ADDRESS);
Log.d(TAG, "Connecting...");
Socket socket = new Socket(address, SERVER_PORT_NUMBER);
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.d(TAG, "I/O created");
message = params[0];
if (!message.equals("stop")) {
sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
private void sendMessage(String message) {
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
Log.d(TAG, "Sent message: " + message);
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "onPostExecute(), s: " + s);
}
Thank you.
The problem is that your BufferedReader only read the first input stream. In order to receive the text after that, you have to re-read the input stream. I do it by recreating the socket when I am done reading, so that I can read next coming data. I am using the following code in my app. You can use this
private ServerSocket serverSocket;
public static final int SERVERPORT = 5000;
Thread serverThread = null;
public void startSocketServer(){
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
public void stopSocket(){
if(serverSocket != null){
try{
serverSocket.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
Log.wtf(TAG,"Socket: New Socket");
serverSocket = new ServerSocket(SERVERPORT);
if(serverSocket == null){
runOnUiThread(new Runnable() {
#Override
public void run() {
startSocketServer();
}
});
return;
}
while (!Thread.currentThread().isInterrupted() && !serverSocket.isClosed()) {
try {
socket = serverSocket.accept();
Log.wtf(TAG,"Socket: Accepting");
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
Log.wtf(TAG,"Socket: Error");
e.printStackTrace();
}
if(Thread.currentThread().isInterrupted()){
Log.wtf(TAG, "Thread Interrupted");
}
if(serverSocket.isClosed()){
Log.wtf(TAG, "serverSocket closed");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
log.info("Connected! Receiving message...");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
try {
while (true) {
String line = in.readLine();
if (line != null) {
log.info(line);
}
else
break;//This will exit the loop and refresh the socket for next data
}
} catch (Exception e) {
log.error("Unexpected exception while sending / receiving messages.");
e.printStackTrace();
}
finally {
in.close();
clientSocket.close();
}
refreshSocket();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void refreshSocket(){
runOnUiThread(new Runnable() {
#Override
public void run() {
stopSocket();
startSocketServer();
}
});
}
Just call startSocketServer() to start the server socket in your code.

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();
}
}
}
}

Java socket client connection and disconnection issue

I made this script:
public class Server {
ServerSocket serv = null;
ObjectInputStream in = null;
ObjectOutputStream out = null;
Socket conn = null;
public Server() {
setLogger(getClass());
setupSocketServer();
listen();
}
public void listen() {
try {
while (true) {
conn = serv.accept();
getLogger().log(new LogRecord(Level.INFO, "Connection established from: " + conn.getInetAddress().getHostAddress()));
out = new ObjectOutputStream(conn.getOutputStream());
in = new ObjectInputStream(conn.getInputStream());
}
}
catch (IOException ex) {
getLogger().log(new LogRecord(Level.SEVERE, "Connection dropped from: " + conn.getInetAddress().getHostAddress()));
}
}
public void setupSocketServer() {
try {
serv = new ServerSocket(Config.PORT_NUMBER, Config.MAX_CONNECTIONS);
getLogger().log(new LogRecord(Level.INFO, "Starting Server on: " + serv.getInetAddress().getHostAddress() + ":" + serv.getLocalPort()));
}
catch (IOException e) {
getLogger().log(new LogRecord(Level.SEVERE, "Socket can not connect to host address"));
System.exit(0);
}
}
public static void main(String[] args) {
new Server();
}
}
But whenever I open my client connection, then close it again and try to re-open, the server has already closed out. I want to be able to keep an infinite connection which allows multiple people to connect. How would I go about doing this?
Try this code for your server,
its made up for multiple client, and the server will remain listening always.
public class ServerTest {
ServerSocket s;
public void go() {
try {
s = new ServerSocket(44457);
while (true) {
Socket incoming = s.accept();
Thread t = new Thread(new MyCon(incoming));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class MyCon implements Runnable {
Socket incoming;
public MyCon(Socket incoming) {
this.incoming = incoming;
}
#Override
public void run() {
try {
PrintWriter pw = new PrintWriter(incoming.getOutputStream(),
true);
InputStreamReader isr = new InputStreamReader(
incoming.getInputStream());
BufferedReader br = new BufferedReader(isr);
String inp = null;
boolean isDone = true;
System.out.println("TYPE : BYE");
System.out.println();
while (isDone && ((inp = br.readLine()) != null)) {
System.out.println(inp);
if (inp.trim().equals("BYE")) {
System.out
.println("THANKS FOR CONNECTING...Bye for now");
isDone = false;
s.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
try {
s.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ServerTest().go();
}
}
Move try/catch block into 'while' loop. Not that it' will make a goot server, bit should survive client disconnects.

Java, problem sending a message with socket connection

I have a problem with my Java program. It has a socket connection between a server and many client. Here is the server (the part which concerns the problem):
private static ArrayList<ParallelServer> clientConnected = new ArrayList<ParallelServer>();
public Server(int port) {
this.port = port;
if (!startServer())
JOptionPane.showMessageDialog(new JFrame(""),
"Error!", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
private boolean startServer() {
try {
server = new ServerSocket(port);
loadDatabase();
} catch (IOException ex) {
ex.printStackTrace();
return false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return true;
}
public void runServer() {
while (true) {
try {
client = server.accept();
ParallelServer pServer = new ParallelServer(client);
clientConnected.add(pServer);
Thread thread = new Thread(pServer);
thread.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void sendBroadcast(String username) throws IOException {
for(int i = 0; i < clientConnected.size(); i++)
clientConnected.get(i).sendAnswer("#change," + username);
}
The parallel server is:
private Socket client;
private InputStreamReader inputstreamreader;
private BufferedReader bufferedreader;
private PrintWriter printwriter;
public ParallelServer(Socket client) {
this.client = client;
}
public void run() {
try {
inputstreamreader = new InputStreamReader(client.getInputStream());
bufferedreader = new BufferedReader(inputstreamreader);
printwriter = new PrintWriter(client.getOutputStream(), true);
String lineread = "";
while (client.isConnected()) {
lineread = bufferedreader.readLine();
doCommand(lineread);
}
} catch (UnknownHostException unhe) {
} catch (InterruptedIOException intioe) {
} catch (IOException ioe) {
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void sendAnswer(String answer) throws IOException {
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.println(answer);
printwriter.flush();
}
And here is the client:
private String serverurl = "localhost";
private int serverport = 7777;
private PrintWriter printwriter;
private InputStreamReader inputstreamreader;
private BufferedReader bufferedreader;
private Socket server;
public Client() {
server = null;
try {
server = new Socket(serverurl, serverport);
server.setSoTimeout(5000);
} catch (UnknownHostException unhe) {
System.out.println("UnknownHostException: " + unhe.getMessage());
} catch (InterruptedIOException intioe) {
System.out.println("Timeout while attempting to establish socket connection.");
} catch (IOException ioe) {
JOptionPane.showMessageDialog(new JFrame(),"Unable to reach the server!","ERROE!",JOptionPane.ERROR_MESSAGE);
}
}
public String sendCommand(String command) throws IOException {
if(server == null) {
try {
server = new Socket(serverurl, serverport);
server.setSoTimeout(5000);
} catch (UnknownHostException unhe) {
System.out.println("UnknownHostException: " + unhe.getMessage());
} catch (InterruptedIOException intioe) {
System.out.println("Timeout while attempting to establish socket connection.");
} catch (IOException ioe) {
JOptionPane.showMessageDialog(new JFrame(),"Unable to reach the server!","ERROR!",JOptionPane.ERROR_MESSAGE);
}
}
if(server != null) {
printwriter = new PrintWriter(server.getOutputStream(), true);
printwriter.println(command);
printwriter.flush();
inputstreamreader = new InputStreamReader(server.getInputStream());
bufferedreader = new BufferedReader(inputstreamreader);
return bufferedreader.readLine();
}
else
return "#serverProblem";
}
The program is a simple online game with turns. Players' turns are created with a queue and when a player passes his turn, the server send a broadcast message which say "Now it is 'Player 1' turn." (for instance). My problem is that when a client receive the message, its like it add the answer "Now it is 'Player 1' turn." to the next message it will receive. In my case: when a player passes his turn, he sends "#passTurn,username". The ParallelServer class polls it from the queue, puts it at the bottom of the queue, sends the client "#ok" to tell it that the turn has changed successfully and tells the Server class to send the broadcast message. Then, when the same client will try do do a further action, it will consider "Now it is 'Player 1' turn." as the answer the server has given to it. Instead, I would like that the server and the clients work as always and when the broadcast message is cought, the client is notified without any collateral effect.
What can I do?
Thanks.
Your bi-directional message passing mechanism should look something like this:
Server:
Wait on any client InputStream
if (broadcast)
broadcast_message()
else
process_message()
Client:
Receiving Thread:
Wait on server broadcast
Sending Thread:
Wait on messages to be sent to server from the User Input
This should do the trick :)
Hope it helps. Cheers!

Categories

Resources