# Senden von Daten nicht direkt möglich?



## mavinatic (30. Sep 2011)

Hallo Community,

ich habe ein Problem und zwar möchte ich jedes mal auf einen bestimmten Tastendruck, Daten an einen Server versenden. Das Problem was ich habe ist, dass der Client aber nicht bei Tastendruck sendet, ich weiß einfach nicht warum?!


```
@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		System.out.println(e.getKeyCode());
		
		if(e.getKeyCode()==config.MOVEMENT_FORWARD)
		{
			Player player = panel.getPlayer(data.getCurrentPlayerName());
			if(player!=null)
			{
				int posY = player.getY();
				
				posY = posY - config.MOVEMENT_SPEED;
				handler.send("POST /refreshPositionSet?game="+data.getCurrentGameName()+"&playerName="+data.getCurrentPlayerName()+"&positionX="+player.getX()+"&positionY="+posY+" URLGS/1.0");
			}
		}
```

Handler.send(String msg):

```
public void send(String msg)
	{
		writer.println(msg);
		writer.flush();
	}
```

Der Writer ist ein PrintWriter.

Ich weiß nicht worans liegen könnte, denn ich mache jedes mal nach einer Nachricht ein flush();


----------



## ARadauer (30. Sep 2011)

mavinatic hat gesagt.:


> Ich weiß nicht worans liegen könnte,..


naja du hast zwei Probleme. Bei Tastendruck wird nicht gesendet. Wird der Tastendruck nicht erkannt oder geht das senden nicht.
Gibt mal einfach eine Consolen Ausgabe in das if(e.getKeyCode()==config.MOVEMENT_FORWARD)

und sende mal automatisch.

Dann wissen wir schonmal wo das Problem liegt...


----------



## mavinatic (30. Sep 2011)

Ich gebe immer die Taste aus welche ich gedrückt habe....also den KeyCode ;-) Das stimmt soweit, es ist nur die Übertragung?! die nicht stimmt


----------



## ARadauer (30. Sep 2011)

mavinatic hat gesagt.:


> es ist nur die Übertragung?


Ist das eine Frage?

Wenn es die Übertragung ist, dann bau dir ein kleines Beispiel wo du die Übertragung testest, inkl lesen auf der anderen Seite... und poste das mal


----------



## mavinatic (30. Sep 2011)

habe ich doch, da oben....in meinem ersten post, steht alles wie ich es mache...es wird einfach nicht direkt geschickt sondern nach ca. 30sekunden!? Was ich nicht verstehen kann?!


----------



## ARadauer (30. Sep 2011)

mavinatic hat gesagt.:


> in meinem ersten post, steht alles wie ich es mache



sorry für mich ist das zuwenig um den fehler genau eingrenzen zu können.
Wie verbindest du dich, wie ließt du auf der anderen Seite?

Mach mal nach dem flush ein close, wird dann sofort gesendet?


----------



## mavinatic (30. Sep 2011)

Dann funktioniert mein Programm nicht mehr  weil ich vorher schon daten an den server sende ;-)

Klasse - DataHandler (Daten werden verarbeitet)

```
package org.game.client;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;

import org.game.gui.MainPanel;
import org.game.ressource.Player;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;


public class DataHandler {
	private Socket socket;
	private PrintWriter writer;
	private BufferedReader reader;
	
	private SAXBuilder xmlParser = null;
	private Thread tReader = null;
	
	private MainPanel panel = null;
		
	public DataHandler(Socket socket, MainPanel panel)
	{
		try
		{
			this.socket = socket;
			this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			this.writer = new PrintWriter(socket.getOutputStream());

			this.panel = panel;
			
			xmlParser = new SAXBuilder();
						
		} catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public void recieve()
	{
		tReader = new Thread() {
			@Override
			public void run()
			{
				try {
					while(true)
					{
						String line = reader.readLine();
						if(line!=null)
						{
//							System.out.println(line);
							processCommand(line);
						}
					}
				} catch (Exception e) {
					// SocketClosedExceptioN!!
				}
			}
		};
		tReader.start();
	}
	
	public void send(String msg)
	{
		writer.println(msg);
		writer.flush();
	}
	
	public Socket getSocket()
	{
		return this.socket;
	}
	
	public void closeConnection(String gamename, String playername)
	{
		try
		{
			send("POST /closeConnection?game="+gamename+"&playerName="+playername+" URLGS/1.0");
			socket.close();	
			reader.close();
			writer.close();
		
		} catch(Exception e){}
	}
	
	public void processCommand(String cmd)
	{
		try
		{
			Document doc = xmlParser.build(new ByteArrayInputStream(cmd.getBytes()));
			
			Element rootElement = doc.getRootElement();
			
			if(rootElement.getName().toUpperCase().equals("REQUEST"))
			{
				Element player = rootElement.getChild("PLAYERS");
				
				List<Element> players = player.getChildren();
				
				Player[] currentPlayers = new Player[players.size()];
				
				for(int i=0;i<players.size();i++)
				{
					String playerName = players.get(i).getChild("NAME").getValue();
					int playerPositionX = Integer.parseInt(players.get(i).getChild("X").getValue());
					int playerPositionY = Integer.parseInt(players.get(i).getChild("Y").getValue());
					currentPlayers[i] = new Player(playerName, playerPositionX, playerPositionY);
				}
				
				panel.setPlayers(currentPlayers);
			}
			if(rootElement.getName().toUpperCase().equals("COMMONREQUEST"))
			{
				Element player = rootElement.getChild("PLAYERS");
				
				List<Element> players = player.getChildren();
				
				Player[] currentPlayers = new Player[players.size()];
				
				for(int i=0;i<players.size();i++)
				{
					String playerName = players.get(i).getChild("NAME").getValue();
					int playerPositionX = Integer.parseInt(players.get(i).getChild("X").getValue());
					int playerPositionY = Integer.parseInt(players.get(i).getChild("Y").getValue());
					currentPlayers[i] = new Player(playerName, playerPositionX, playerPositionY);
					System.out.println(currentPlayers[i].getName());
				}
				
				panel.setPlayers(null);
				panel.setPlayers(currentPlayers);
			}
		} catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
```

Klasse - ControlListener (Key & Mouse -Aktionen werden verarbeitet)

```
package org.game.gui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import org.game.client.Configuration;
import org.game.client.DataHandler;
import org.game.client.SharedData;
import org.game.ressource.Player;

public class ControlListener implements KeyListener, MouseListener {
	
	private Configuration config = null;
	private DataHandler handler = null;
	private SharedData data = null;
	private MainPanel panel = null;
	
	public ControlListener(MainPanel panel, SharedData data) throws Exception
	{
		this.panel = panel;
		
		this.handler = panel.getDataHandler();
		
		this.data = data;
		
		this.config=data.getConfiguration();
		
		
		if(data.getConfiguration()==null)
		{
			throw new Exception ("No Configuration File");
		}	
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		System.out.println(e.getKeyCode());
		
		if(e.getKeyCode()==config.MOVEMENT_FORWARD)
		{
			Player player = panel.getPlayer(data.getCurrentPlayerName());
			if(player!=null)
			{
				int posY = player.getY();
				
				posY = posY - config.MOVEMENT_SPEED;
				System.out.println("POST /refreshPositionSet?game="+data.getCurrentGameName()+"&playerName="+data.getCurrentPlayerName()+"&positionX="+player.getX()+"&positionY="+posY+" URLGS/1.0");
				handler.send("POST /refreshPositionSet?game="+data.getCurrentGameName()+"&playerName="+data.getCurrentPlayerName()+"&positionX="+player.getX()+"&positionY="+posY+" URLGS/1.0");
			}
		}
		
		if(e.getKeyCode()==config.MOVEMENT_BACKWARD)
		{
			Player player = panel.getPlayer(data.getCurrentPlayerName());
			if(player!=null)
			{
				int posY = player.getY();
				
				posY = posY + config.MOVEMENT_SPEED;
				System.out.println("POST /refreshPositionSet?game="+data.getCurrentGameName()+"&playerName="+data.getCurrentPlayerName()+"&positionX="+player.getX()+"&positionY="+posY+" URLGS/1.0");
				handler.send("POST /refreshPositionSet?game="+data.getCurrentGameName()+"&playerName="+data.getCurrentPlayerName()+"&positionX="+player.getX()+"&positionY="+posY+" URLGS/1.0");
			}
		}
		
		if(e.getKeyCode()==config.MOVEMENT_LEFT)
		{
			Player player = panel.getPlayer(data.getCurrentPlayerName());
			if(player!=null)
			{
				int posX = player.getX();
				
				posX = posX - config.MOVEMENT_SPEED;
				System.out.println("POST /refreshPositionSet?game="+data.getCurrentGameName()+"&playerName="+data.getCurrentPlayerName()+"&positionX="+posX+"&positionY="+player.getY()+" URLGS/1.0");
				handler.send("POST /refreshPositionSet?game="+data.getCurrentGameName()+"&playerName="+data.getCurrentPlayerName()+"&positionX="+posX+"&positionY="+player.getY()+" URLGS/1.0");
			}
		}
		
		if(e.getKeyCode()==config.MOVEMENT_RIGHT)
		{
			Player player = panel.getPlayer(data.getCurrentPlayerName());
			if(player!=null)
			{
				int posX = player.getX();
				
				posX = posX + config.MOVEMENT_SPEED;
				System.out.println("POST /refreshPositionSet?game="+data.getCurrentGameName()+"&playerName="+data.getCurrentPlayerName()+"&positionX="+posX+"&positionY="+player.getY()+" URLGS/1.0");
				handler.send("POST /refreshPositionSet?game="+data.getCurrentGameName()+"&playerName="+data.getCurrentPlayerName()+"&positionX="+posX+"&positionY="+player.getY()+" URLGS/1.0");
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

}
```

Klasse - MainPanel (Oberfläche zum zeichnen)

```
package org.game.gui;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.net.Socket;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import org.game.client.DataHandler;
import org.game.client.SharedData;
import org.game.ressource.Player;

public class MainPanel extends JPanel {
	/*
	 * GameInfo
	 */
	private DataHandler handler = null;
	private Player[] currentPlayers = null;
	private SharedData data = null;
	
	/*
	 * Graphical Inits.
	 */
	private Image backBuffer = null;
	Image img = null; // TestImage
	
	/*
	 * Control Listener/Panels
	 */
	private ControlListener listener = null; 
	
	public MainPanel(SharedData data, Socket socket) throws Exception
	{
		this.data = data;
		this.handler = new DataHandler(socket, this);
		
		this.listener = new ControlListener(this, data);
		
		testPrepare();
		init();
		gameloop();
	}
	
	private void testPrepare() {
		handler.send("POST /createGame?name="+data.getCurrentGameName()+"&maxPlayers=10 URLGS/1.0");
		handler.send("POST /addNewPlayer?playerName="+data.getCurrentPlayerName()+"&playerPositionX=100&playerPositionY=500&game="+data.getCurrentGameName()+" URLGS/1.0");
//		handler.closeConnection(data.getCurrentGameName(), data.getCurrentPlayerName());
	}
	
	/*
	 * Initialisieren
	 * Spielname festlegen
	 * 
	 * Spieler / Position abfragen
	 */
	public void init()
	{
		setFocusable(true);
		requestFocus();
		setDoubleBuffered(false);
		addKeyListener(listener);
		
		try {
			img = ImageIO.read(new File("pic/blue.PNG"));
		} catch(Exception e)
		{
			e.printStackTrace();
		}
		
		handler.recieve();
		handler.send("GET /commonRequest?game=XYZ URLGS/1.0");
		
		//Draw BackBufferImage
		renderScreen();
		//Set BackBuffer to Front
		repaint();
	}
	
	private void gameloop()
	{
		Thread loop = new Thread() {
			@Override
			public void run() 
			{
				try
				{
					while(true)
					{
						/*
						 * Playerpositions
						 */
						handler.send("GET /refreshPositionGet?game=XYZ URLGS/1.0");
						/*
						 * Maybe healthpoints / or smth like that
						 * Just space for later ;)
						 */
						renderScreen();
						repaint();
						Thread.sleep(data.getRate());
					}
				} catch(Exception e)
				{
					e.printStackTrace();
				}
			}
		};
		loop.start();
	}
	/*
	 * 
	 * Graphic Methods
	 * 
	 */
	public void renderScreen()
	{
		if(backBuffer==null)
		{
			createBackBuffer();
		} else
		{
			Graphics graph = backBuffer.getGraphics();
			
			graph.setColor(Color.WHITE);
			graph.fillRect(0, 0, getWidth(), getHeight());
			
			if(currentPlayers!=null)
			{
				for(int i=0;i<currentPlayers.length;i++)
				{
					graph.drawImage(img, currentPlayers[i].getX(), currentPlayers[i].getY(), this);
				}
			}
			
		}		
	}
	
	@Override
	public void paint(Graphics g)
	{
		if(backBuffer!=null)
		{
			g.drawImage(backBuffer, 0, 0, null);
		} else 
		{
			createBackBuffer();
			renderScreen();
		}
	}
	
	private void createBackBuffer() 
	{
		backBuffer = createImage(getWidth(), getHeight());
	}
	
	
	/*
	 * GETTER & SETTER
	 */
	public void setPlayers(Player[] players)
	{
		this.currentPlayers = players;
	}
	
	public Player[] getPlayers()
	{
		return this.currentPlayers;
	}
	
	public Player getPlayer(String name)
	{
		for(int i=0;i<currentPlayers.length;i++)
		{
			if(currentPlayers[i].getName().equals(data.getCurrentPlayerName()))
			{
				return currentPlayers[i];
			}
		}
		return null;
	}
	
	public DataHandler getDataHandler()
	{
		return this.handler;
	}
}
```

Ich habe nun einen Test gemacht! Und zwar bei der send-Methode 2 Ausgaben:


```
public void send(String msg)
	{
		if(!msg.equals("GET /refreshPositionGet?game=XYZ URLGS/1.0"))
		{
			System.out.println(msg);
		}
		
		writer.println(msg);
		writer.flush();
		if(!msg.equals("GET /refreshPositionGet?game=XYZ URLGS/1.0"))
		{
			System.err.println(msg);
		}
	}
```

Also es werden alle Ausgaben gesendet....weil jede Tasten eingabe wird mit dem flush verarbeitet....also muss das Problem Serverseitig liegen!?


----------

