# Client server problem



## java66 (16. Jan 2010)

Hallo zusammen, habe ein problem und hoffe das jemand von euch mir mal wieder eine hilfe stellung geben kann.

folgendes szenario.

Client wurde gestartet.

client besitzt eine funktionen sendFileVector()
-in dieser funktion wird ein vector<Files> v übergeben
-und auf jedes file wird eine prozedure auf dem server angewandt

ablauf dieser funktion

i<v.getsize
  sendfilenametoServer(v.get(i).getname)
  sendefiletoserver(v.get(i))
  getresultfromServer() :String
 i++

normalerweise macht er dann auch den ersten durchlauf für den ersten vector , rufe ich nun aber einen zweiten vector auf(nicht paralel sondern nachdem der erste abgearbeitet ist bleibt er beim read inputstream stecken).

hier mal meine klasse zum (nur der client) zum anschauen vileicht wisst ihr ja was ich falsch mache finde niemanden der mir auch nur einen ansatzt geben konnte.wenn jemand bereit wäre sich den ablauf anzuschauen dann würde ich auch die server klasse posten.ist nicht viel denke das das nur eine kleinigkeit ist.

```
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JOptionPane;


public class NewClientServerCon implements Runnable {
//	-------------------------------------------------------------------------KlassenVariablen--------------
	String serverName;
	String FileName="deafult";
	Thread cleintThread = new Thread(this);
	File file;
	int port;
	HashMap<String,String> resultMap=new HashMap<String,String>();
	Vector<File> caseFiles=null;
	Socket socket;
	String fileName;
	Vector<File> files=null;
	int filescnt=0;
	InputStream fileinputStream = null;
	DataOutputStream dos=null ;
	DataInputStream dis=null;
	boolean isDone=false;
	int cnt=0;
	int actcaseid=0;
//	-----------------------------------------------------------------------------KONSTRUKTOR--------------
	public NewClientServerCon(String serverName,int port)
	{
		
		this.serverName=serverName;
		this.port=port;
		initServerConnection();
		System.out.println("NEWCLIENT KONSTRUKTOR END");
	}
//	-----------------------------------------------------------------------------OKERRORDIALOG------------
	public void okErrorDialog(String message,String title)
	{
	JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);	
	}
//	------------------------------------------------------------------------------INITSERVER---------------------
	public boolean initServerConnection()
	{
		try 
		{
			socket=new Socket(serverName,port);
			dos = new DataOutputStream (socket.getOutputStream());
			dis=new DataInputStream (socket.getInputStream());
			System.out.println("initSERVERCON end");
			return true;
		} 
		catch (UnknownHostException e) {okErrorDialog("host not found.!\nPlease check settings","connection failed!");e.printStackTrace();return false;} 
		catch (IOException e) {okErrorDialog("Connection to server failed.\nPlease restart and try again","connection failed!");e.printStackTrace();return false;}
		catch(Exception e){okErrorDialog("Connection to server failed.\nPlease restart and try again","connection failed!");e.printStackTrace();return false;}

		
	}
//	----------------------------------------------------------------------------isATTCONNECTED-----------------
	public boolean isConnected()
	{
		if(this.socket.isConnected())return true;
		else return false;	
	}
//	--------------------------------------------------------------------------------DOCASE()---------------------
	public void setTestval(Vector<File> v, int caseID)
	{
		this.caseFiles=v;
		this.actcaseid=caseID;	
	}
/*
 * liefert null wenn nicht connected oder wenn ein file nicht existiert ansonsten immer die resultMap
 * */	
	public synchronized HashMap<String,String> doCase()
	{
		System.out.println("DO CASE STARTET");
		boolean failexist=false;
		int cid=this.actcaseid;
		HashMap<String,String> resultMap=new HashMap<String,String>();
		if(this.caseFiles==null)
		{ 
			return null;
		}
		if(!isATTConnected())
		{
			okErrorDialog("Client is not connected to Server.\nPlease connect and retry", "Connection missing");
			return null;
		}
		else if(isConnected())
		{
			for(int i=0;i<this.caseFiles.size();i++)
			{
				if(!new File(this.caseFiles.get(i).getAbsolutePath()).exists())
				{
					okErrorDialog("one ore more files for this case doesnt exist caseID "+cid, "File not found");
					return null;
				}
			}

			//beginne nun die procedure wenn alles in ordnung war
			for(int j=0;j<this.caseFiles.size();j++)
			{
			
				System.out.println("CLIENT->sendingInformation>>>>");
				failexist=sendInformation(this.caseFiles.get(j).getName(),"CMD",""+this.caseFiles.size());
				System.out.println("CLIENT->Information send<");
				
				failexist=send(this.caseFiles.get(j), ""+cid);
				if(failexist){break;}
				String resultforCase=getResult();
				System.out.println("before tokeniz result show"+resultforCase);
				if(resultforCase!=null && resultforCase.contains(","))
				{
					StringTokenizer st=new StringTokenizer(resultforCase,",");
					String keyid=st.nextToken();
					String keyVal=st.nextToken();
					resultMap.put(keyid, keyVal);
				}else return null;
			}
			
		}
		return resultMap;
	}
//	-----------------------------------------------------------------------------SENDINFORMATION-------------------
	private boolean sendInformation(String FileName, String cmd,String filecnt) {
		try {
			dos.writeUTF(FileName + "," + cmd+","+filecnt);
			System.out.println("Client write information.....end");
			return true;
			//			dos.flush();
		} catch (IOException e) 
		{
			
			System.out.println("Send Information Fehler");
			e.printStackTrace();
			return false;
		}
	}
//	------------------------------------------------------------------------SENDFILE probiere fileinputStream leeren---
	private synchronized boolean send(File f, String caseID) 
	{
		if (socket == null)
		{
			okErrorDialog("Client is not connected.Please connect and try\nagain.", "Connection failed");
			return false;
		}
		if(f==null||!f.exists())
		{
			okErrorDialog("One or more files for case doesnt exists!.\n caseID "+caseID, "File not found");
			return false;
		}
		
		System.out.println("sending File...."+f.getName());
		byte[] buffer = new byte[16384];
		
		try {
				fileinputStream = new FileInputStream(f);
				while (fileinputStream.available() > 0) 
				{
				dos.write(buffer, 0, fileinputStream.read(buffer));
				}
				dos.flush();
//				fileinputStream.close();
				System.out.println("send!!");
				return false;
			} 
		catch (FileNotFoundException e) 
			{
			System.out.println("FILENOTFOUND in sendFile");
			e.printStackTrace();
			return true;
			} 
		catch (IOException e) 
			{
			System.out.println("IO in sendFile");
			e.printStackTrace();
			return true;
			}
	}
//	--------------------------------------------------------------------------setcaseFiles--------------
	public void setcaseFiles(Vector<File> v)
	{
		this.caseFiles=v;
	}
	//	--------------------------------------------------------------------------getRESULT--------------
/*
 * Wenn ein resultat kommt dann return im format caseID als key, resultat as 
 * string an aufruf stelle tokenizen
 * */
	public String getResult()
		{
			try 
			{
//				dis.notifyAll();
				String result = dis.readUTF();
				System.out.println("getResult for file="+result);
				System.out.println(result);
				if(result!=null)
					{
					return result;
					}
				else result=null;
			} 
			catch (IOException e) 
			{
				e.printStackTrace();}
				return null;
			}
//	-----------------------------------------------------------------------------------------------------

	@Override
	public void run() 
	{	
		doCase();
		
	}
}
```


----------



## vsk (18. Jan 2010)

java66 hat gesagt.:


> client besitzt eine funktionen sendFileVector()



Wo?(Zeile)
Ich finde die Methode sendFileVector() nicht.


----------



## java66 (19. Jan 2010)

Hallo das problem besteht weiterhin.

hier mal eine neuere version 3 wochen hänge ich jetzt dran und es klappt immernoch nicht.
Brauche wirklich dringend hilfe bei der Fehler suche/korrektur.

main() wird später als funktion benutzt um einen vector mit files zu bearbeiten also main()=sendVectorFiles() im hauptprogramm.

ablauf:

1)client verbindet sich zu server und verbindung steht bis das client programm beendet wird

2)client ruft vector<File> v auf und solange i<v.getsize()
-client->sende dateinamen von v.get(i)
-client->sende datei v.get(i)
-client->empfange resultat vom server für v.get(i)
i++
3)client ruft neuen vector auf.... wieder der selbe ablauf

PROBLEM -wenn ich sage ich will in einer for 100 Vector<File> bearbeiten macht er bei 6 schluss

brauche dringend hilfe seit 3 wochen am selben problem.

wählt irgendwelche dateien aus .txt.bat..... im moment teste ich nur das dateien hin schicken und einen festen wert zurück bekommen mehr brauch ich auch nicht

DANKEEE im Voraus

```
import java.io.*;
import java.net.*;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class Client
{
  private Socket socket;
  private DataInputStream dis=null;
  private DataOutputStream dos=null;
  boolean connection;
  boolean streamsonline;
  Vector<File> caseFiles=null;
  private FileInputStream fileinputStream=null;
  private boolean connected;
  
// -----------------------------------------------------------------------------OKERRORDIALOG------------
  private void setcaseFiles(Vector<File> caseFiles){this.caseFiles=caseFiles;}
// -----------------------------------------------------------------------------OKERRORDIALOG------------
  private boolean connectStream()
  {
	try 
	{
		dis=new DataInputStream(socket.getInputStream());
		dos=new DataOutputStream(socket.getOutputStream());
		connected=true;
		return true;
	} 
	catch (IOException e) 
	{
		System.err.println("Streams not initialized!!");
		e.printStackTrace();
		connected =false;
		return false;
	}
		
  }
// -----------------------------------------------------------------------------OKERRORDIALOG------------
  private boolean connect2Server()
  {
	try 
	{
		socket=new Socket("localhost",4711);
		return true;
	} 
	catch (UnknownHostException e) 
	{
		System.err.println("UNKNOWN HOST localhost");
		e.printStackTrace();
		connected=false;
		return false;
	} 
	catch (IOException e) 
	{			
		System.err.println("IOException connectClient localhost");
		e.printStackTrace();
		connected=false;
		return false;
	}
  }
// -----------------------------------------------------------------------------OKERRORDIALOG------------
  public void okErrorDialog(String message, String title) 
  {
		JOptionPane.showMessageDialog(null, message, title,JOptionPane.ERROR_MESSAGE);
  }
// -----------------------------------------------------------------------------OKERRORDIALOG------------
  public boolean sendUTF(String s)
  {
	try
	{
		dos.writeUTF(s);
		dos.flush();
		return true;
	} 
	catch (IOException e) {e.printStackTrace();return false;}
	
  }
// -----------------------------------------------------------------------------OKERRORDIALOG------------
  private boolean send(File f, String caseID) 
  {
	
	if (socket == null) 
	{
	okErrorDialog("AClient is not connected.Please connect and try\nagain.","Connection failed");
	return false;
	}

	if (f == null || !f.exists())
	{
	okErrorDialog("One or more files for case doesnt exists!.\n caseID "+ caseID, "File not found");
	return false;
	}
		
	System.out.println("sending File...." + f.getName());

	byte[] buffer = new byte[16384];
	
	try 
	{
		fileinputStream = new FileInputStream(f);
		
		while (fileinputStream.available() > 0) 
		{
			dos.write(buffer, 0, fileinputStream.read(buffer));
		}
		dos.flush();
		
		System.out.println("send!!");
		return true;
	} 
	catch (FileNotFoundException e) 
	{
		System.out.println("FILENOTFOUND in sendFile");
		e.printStackTrace();
		return false;
	} 
	catch (IOException e) 
	{
		System.out.println("IO in sendFile");
		e.printStackTrace();
		return false;
	}
	finally
	{	
		try 
		{
			fileinputStream.close();
		} 
		catch (IOException e){e.printStackTrace();}
	}
 }
//-----------------------------------------------------------------------------OKERRORDIALOG------------
  private boolean sendInformation(String FileName, String cmd, String filecnt) 
  {
	try 
	{
		dos.writeUTF(FileName + "," + cmd + "," +filecnt);
		System.out.println("Client write information.....end");
		dos.flush();
		return true;
	} 
	catch (IOException e) 
	{
		System.out.println("Send Information Fehler");
		e.printStackTrace();
		return false;
	}
  }
//-----------------------------------------------------------------------------OKERRORDIALOG------------
  private synchronized boolean startProcedure()
  {

	boolean procedureOK=true;

	if(connection && streamsonline)
	{
		for(int i=0;i<caseFiles.size();i++)
		{
			if(procedureOK==false)
			{
				try 
				{
					dos.writeUTF("q");
					return false;
				} catch (IOException e) 
				{
					e.printStackTrace();
				}
				return false;
			}
			File actScript=caseFiles.get(i);
			if(actScript==null||!actScript.exists())
			{
				procedureOK=false;
				try 
				{
				 dos.writeUTF("q");
				} catch (IOException e) {e.printStackTrace();}
				break;
			}
//			if(!socket.isConnected()||socket.isClosed())
//			{
//				System.out.println("Connection closed");
//				try 
//				{
//				dis.close();		
//				dos.close();
//				procedureOK=false;
//				break;
//				} 
//				catch (IOException e) 
//				{
//					e.printStackTrace();
//					procedureOK=false;
//					okErrorDialog("Client not connected", "Connection failed");
//					break;
//				}
//			}
			
			System.out.println("**************CLIENT STARTED*******************");
			
			if(!sendInformation(actScript.getName(), "cmd", "filecnt"))
			{
				procedureOK=false;
				try 
				{
					dos.writeUTF("q");
				} 
				catch (IOException e) {e.printStackTrace();}
				break;
			}
			System.out.println("Client send message");
			System.out.println("sending File");

			if(!send(actScript, "1")){procedureOK=false;break;}
			
			System.out.println("CLIENT WAITING FOR SERVER ANSWER....");
			
			try 
			{
				String received=dis.readUTF();
				if(received.equals("1"))procedureOK=true;
				else 
				{
					System.out.println("failed Server Res= > "+received);
					procedureOK=false;
					
				}
			} 
			catch (IOException e)
			{
				e.printStackTrace();
				procedureOK=false;
				break;
			}
			System.out.println("END OF PROCEDURE FOR SCRIPT ="+actScript.getName());
	        System.out.println("PROCEDURE IS ="+procedureOK);
		}
		return procedureOK;
	}
	else 
	{
		System.out.println("connection or streams not online");
		return false;
	}
  }
//-----------------------------------------------------------------------------OKERRORDIALOG------------
  private boolean closeConnection()
  {
	try 
	{
		if(dos!=null)dos.close();
		if(dis!=null)dis.close();
		if(socket!=null)socket.close();
		System.out.println("Connection end");
		return true;
	} 
	catch (IOException e) 
	{
		e.printStackTrace();
		return false;
	}
  }
//-----------------------------------------------------------------------------OKERRORDIALOG------------

  public static void main(String args[])
  {
	JFileChooser choos=new JFileChooser(".");
	Vector<File> v=new Vector<File>();
	choos.showOpenDialog(null);
	v.add(choos.getSelectedFile());
	
	final Client client=new Client();
	client.connection= client.connect2Server();
	client.streamsonline= client.connectStream();
	client.setcaseFiles(v);
//	client.startProcedure(v);
	Thread t1=new Thread(new Runnable(){

		@Override
		public void run() 
		{
			for(int i=0;i<10;i++)
			{
				client.startProcedure();	
			}
			
		}
		
		
	});
	
	//dies ist ein test um einen zweiten durchlauf zu testen
	t1.start();
	try {
		Thread.sleep(20000);
	} catch (InterruptedException e) 
	{
		e.printStackTrace();
	}
	//-----------------------------------------------------
	//eigentlich soll die connection nur vom benutzter geclosed werden
	//solange das programm laeuft soll die funktion main immerwieder neue vectoren ubergeben und diese ausfuhren
	System.out.println("ENDE");
  }	
}
```


```
import java.net.*;
import java.util.StringTokenizer;

import java.io.*;

import javax.swing.JOptionPane;

public class Server 
{

  private DataOutputStream dos = null;
  private DataInputStream dis = null;
  private Socket socket = null;
  private ServerSocket serversocket = null;
  private String basePath = "c:/tmpServer/";
  private FileOutputStream fileoutStream = null;
  private ServerExecuter scriptexecuter = new ServerExecuter();
 
  
  
 //-------------------------------------------------------------------------------//
 private boolean closeConnection()
 {
   try 
   {
   dos.close();
   dis.close();
   socket.close();
   serversocket.close();
   return true;
   } 
   catch (IOException e) {e.printStackTrace();return false;}	
 }
	
 //-------------------------------------------------------------------------------//
 private File receiveFile(String filename) 
 {
   File base = new File(basePath);
  
   File toExecfile = new File(basePath + filename);
		try 
		{
			
			if (base == null || !base.exists()) 
			{
				System.out.println("return basePath problem on server");
				return null;
			}
			
			if (!toExecfile.exists())toExecfile.createNewFile();
			
			fileoutStream = new FileOutputStream(toExecfile);
			
			byte[] buffer = new byte[1024];
			
			while (dis.available() > 0) 
			{
				int bytesRead = dis.read(buffer);
				if (bytesRead == -1)break;
				fileoutStream.write(buffer, 0, bytesRead);
			}
			
			fileoutStream.flush();
			fileoutStream.close();
			
			System.out.println(getClass() + " Server>resiveFile=100%");
			
			return toExecfile;
		} 
		catch (FileNotFoundException e) 
		{
			e.printStackTrace();
			okErrorDialog("file for tmp scriptFolder not found!","ATT:File not found");
			return null;
		} 
		catch (IOException e) 
		{
			okErrorDialog("file for tmp scriptFolder not found!","ATT:File not found");
			e.printStackTrace();
			return null;
		}
		finally
		{
			try 
			{
			fileoutStream.close();
			} 
			catch (IOException e){e.printStackTrace();}
		}
	}
 //-------------------------------------------------------------------------------//
  public void okErrorDialog(String message, String title) 
  {
		JOptionPane.showMessageDialog(null, message, title,JOptionPane.ERROR_MESSAGE);
  }

 //-------------------------------------------------------------------------------//
  private void sendDefaults()
  {
		try 
		{
			dos.writeUTF("0");
			dos.flush();
//			sendOutputFile("0");
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
  }
 //-------------------------------------------------------------------------------//
  private synchronized void startServing() 
  {
		try 
		{
			
			serversocket = new ServerSocket(4711);
			System.out.println("****************SERVER IN SERVING MOD*********************");
			System.out.println("Server is started...\nwait for client...");
			socket = serversocket.accept();
			dos = new DataOutputStream(socket.getOutputStream());
			dis = new DataInputStream(socket.getInputStream());
		} catch (IOException e) {
			System.out.println("Startserving failed");
			e.printStackTrace();
			closeConnection();
			startServing();
		}
		
//	
			while (socket.isBound()) 
			{
				System.out.println("Server rececived Connection ");
				String reived;
				
				try 
				{
					reived = dis.readUTF();
//					if(reived.equals("q"))break;
					System.out.println("Received from client > " + reived);
					StringTokenizer st=new StringTokenizer(reived,",");
					if(st.countTokens()!=3)
					{
						sendDefaults();
					}
					else
					{
						String filename=st.nextToken();
						String cmd=st.nextToken();
						String id=st.nextToken();
						File f=receiveFile(filename);
						if(f==null)
						{
							sendDefaults();break;
						}
					
						if(f.exists())
						{
//							int res=scriptexecuter.executeFile(f);
							int res=1;
							dos.writeUTF(""+1);
							if(res!=1)
							{
								sendDefaults();
							}
						}
						else 
						{
							sendDefaults();
						}
					}
				} 
				catch (IOException e) 
				{
					e.printStackTrace();
					closeConnection();
					System.out.println(" Connection Closed ConnectionProblem whileSocket.bound!");
					break;
				}
				
				System.out.println("Server send message");
				System.out.println("***************SERVER HAS FINISHED wait for next File");
			}
		
		startServing();
	}
	
 //-------------------------------------------------------------------------------//
  public static void main(String args[])
  {
	  Thread t1=new Thread(new Runnable(){
		public void run() 
		{
		Server server=new Server();
		server.startServing();
		}
    		
        });
     t1.start();
 //-------------------------------------------------------------------------------//

}
}
```


----------



## java66 (21. Jan 2010)

hab esw selbst hinbekommen der fehler lag in einer anderen klasse die einen falschen wert zurück lieferte 
und dieser fehler wurde von mir nicht abgefangen dies führte dazu das der genau ablauf von out und red nicht synchron war.

danke trotzdem gruß


----------

