Incorrect data from server

Hello.
I’m working on simple real time 2D multiplayer shooter and now I started working on server.
To connect with server I decide to use DataInputStream and DataOutputStream.
For now I have simple test:

  • if space key is pressed data are sending to server
  • server recognizing data type and sending this data to others player (in theory)
  • client/player receiving data from server
    Connecting is working sending data to server and receiving also. Unfortunately weary often I’m getting wrong data
    and I don’t know why.
    Some code

I’m sending this data when space is pressed (this work fine)


Connector.getInstance().getOutToServer().writeInt(667);
Connector.getInstance().getOutToServer().writeInt(13);
Connector.getInstance().getOutToServer().flush();
Connector.getInstance().getOutToServer().close();

Server thread (also working fine)


public void run() {
		int gameId = 0;
		int playerData = 0;
		try {
			iss = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
			oss = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
			while (true){
				gameId = iss.readInt();
				if(gameId == 667) {
					playerData = iss.readInt();
					for (int i = 0; i <= 9; i++) {
						//if (clients[i] != this) {
							if (clients[i] != null){
								System.out.println("---sending: "+gameId+" "+playerData);
								clients[i].oss.writeInt(667);
								clients[i].oss.writeInt(13);
								clients[i].oss.flush();
							}
						//}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

Recipient thread (place where I’m geting bad data)


public void run(){
		try {
			while(true){
				data = Connector.getInstance().getFromServer().readInt();
				if(data == 667) {
					int i = Connector.getInstance().getFromServer().readInt();
					System.out.println("byte b: " + data + " int: "+i);
				}
				Thread.sleep(1);
			}
			//Connector.getInstance().setClosed(true);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

The ‘i’ variable very often displaying strange number (0 and 155) but always should be 13 why this happening and how to fix it?
I hope it’s enough information.

Are you sending data in different threads of the same app?

yes

Well then you have your answer. Make sure to properly synchronized access to the Output streams :wink:

You right ra4king.
After few hours I back to this problem and now I see, Output streams wasn’t properly synchronized (he wasn’t synhtonized at all).
Thanks for help