CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    May 2012
    Posts
    8

    socket saving file

    yo there! Im working in a server based on sockets , in fact I already have the code but im lost , because I dont know how to embeds a small code and how to modify the code
    Heres the server code [runs, listen , accept connections, and relays messages]
    Code:
    package servidor;
    
    
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketTimeoutException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
     
    
     
    
    public class Servidor implements Runnable{
    	private static final Logger Logger = LoggerFactory.getLogger(Servidor.class);
    	private ServerSocket server;
    	private List<Atendente> atendentes;
    
    	private boolean inicializado;
    	private boolean ejecutando;
    	private Thread thread;
    
    	public Servidor(int porta) throws Exception {
    		atendentes = new ArrayList<Atendente>();
    		inicializado = false;
    		ejecutando = false;
    		open(porta);
    	}
    	
    	private void open(int porta) throws Exception{
    		Logger.info("Petición de conexión");
    		server = new ServerSocket(porta);
    		inicializado = true;
    	}
    	
    	private void close(){
    		Logger.info("Cierre de conexión");
    		for (Atendente atendente : atendentes){
    			try{
    				atendente.stop();
    				}
    			catch(Exception e){
    				System.out.println(e);
    				}
    			
    		}
    		try {
    			server.close();
    		}
    		catch(Exception e){
    				System.out.println(e);	
    			}
    			server = null;
    			inicializado = false;
    			ejecutando = false;
    
    			thread = null;
    				
    			
    		
    		}	
    
    	
    
    	public void start(){
    		Logger.info("Servidor up and running");
    		if (!inicializado || ejecutando) {
    		return;
    		}	
    		ejecutando = true;
    		thread = new Thread(this);
    		thread.start();
    	}
    	public void stop() throws Exception {
    		Logger.info("Cierre de server y threads");
    	    ejecutando = false;
    	    thread.join();
    	}
    
    	public void run(){
    		System.out.println("Esperando conexiones.");
    		while (ejecutando){
    		try {
    			server.setSoTimeout(2500);
    			Socket socket = server.accept();
    			System.out.println("Conexión establecida.");
    	
    			Atendente atendente = new Atendente(socket);
    			atendente.start();
    			atendentes.add(atendente);
    			}
    		catch (SocketTimeoutException e) {
    	
    			}
    		catch (Exception e) {
    		System.out.println(e);
    		break;	
    			}
    		}
    		close();
    	}	
    	public static void main(String[] args) throws Exception {
    	Logger.info("Inicio de servidor");
    	System.out.println("Iniciando server.");
    	Servidor servidor = new Servidor(2525);
    	servidor.start();
    	System.out.println("Presione Enter para cerrar el server");
    	new Scanner(System.in).nextLine();
    	System.out.println("Cerrando servidor");
    	servidor.stop();
    	Logger.info("Fin de servidor =p" );
    	}
    }
    heres the class that supports the server
    Code:
    package servidor;
    
    import java.net.Socket;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.SocketTimeoutException;
    
    public class Atendente implements Runnable {
    
    	private Socket socket;
    	
    	private BufferedReader in;
    	private PrintStream out;
    	
    	private boolean	 inicializado;
    	private boolean ejecutando;
    	
    	private Thread thread;
    
    	public Atendente(Socket socket) throws Exception {
    		this.socket = socket;
    		this.inicializado = false;
    		this.ejecutando = false;
    
    		open();
    
    	}
    
    	private void open() throws Exception {
    		try{
    		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));	
    		out = new PrintStream(socket.getOutputStream());
    		inicializado = true;		
    		}
    		catch(Exception e){
    		close();
    		throw e;
    
    		}		
    	}
    	private void close() {
    
    		if (in != null){
    			try{
    			in.close();
    			}
    		catch (Exception e){
    			System.out.println(e);
    			}
    		}
    		if (out != null){
    			try{
    			out.close();
    			}
    		catch (Exception e){
    			System.out.println(e);
    			}
    		}
    
    			try{
    			socket.close();
    			}
    		catch (Exception e){
    			System.out.println(e);
    			}
    		in=	null;
    		out = 	null;
    		socket= null;
    		inicializado = false;
    		ejecutando = false;
    		thread = null;
    
    
    	
    
    
    	}
    
    	public void start(){
    		if(!inicializado || ejecutando){
    			return;
    		}
    		ejecutando = true;
    		thread = new Thread(this);
    		thread.start();	
    	
    
    	}
    
    	public void stop() throws Exception{
    		ejecutando = false;
    		thread.join();
    
    	}
    	public void run(){
    		while (ejecutando){
    			try {
    			socket.setSoTimeout(2500);
    			String mensaje = in.readLine();
    		System.out.println("Mensaje recibido de los clientes [" +
    		socket.getInetAddress().getHostName() +
    		":"+
    		socket.getPort()+			
    		"]:"+
    		mensaje);
    	if ("Fin".equals(mensaje)) {
    		break;
    		}
    	out.println(mensaje);
    		}
    		catch (SocketTimeoutException e){
    
    		}
    		catch (Exception e){
    			System.out.println(e);
    			break;
    		}
    
    	}
    	System.out.println("Cerrando conexión");
    	close();
    
    	}
    
    }
    and heres the client
    Code:
    package cliente;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.Socket;
    import java.net.SocketTimeoutException;
    import java.util.Scanner;
    
    public class Cliente implements Runnable{
    	private Socket socket;
    	private BufferedReader in;
    	private PrintStream out;
    	private boolean inicializado;
    	private boolean ejecutando;
    	private Thread thread;
    	public Cliente(String endereco, int porta) throws Exception {
    	inicializado = false;
    	ejecutando = false;
    
    	open(endereco,porta);
    
    	}
    	private void open(String endereco, int porta) throws Exception {
    	try {
    	socket = new Socket(endereco,porta);
    	in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    	out= new PrintStream(socket.getOutputStream());
    	inicializado = true;
    	}
    	catch (Exception e){
    		System.out.println(e);
    		close();
    		throw e;
    
    	}
    
    }
    
    	private void close(){
    	if (in != null){
    		try {
    			in.close();
    			}
    		catch (Exception e){
    			System.out.println(e);
    		
    			}
    		}
    	if (out != null){
    		try {
    			out.close();
    			}
    		catch (Exception e){
    			System.out.println(e);
    		
    			}
    		}	
    	if (socket != null){
    		try {
    			socket.close();
    			}
    		catch (Exception e){
    			System.out.println(e);
    		
    			}
    		}	
    	in = null;
    	out = null;
    	socket = null;
    	inicializado = false;
    	ejecutando = false;
    
    	thread = null;
    
    	}
    	
    	public void start(){
    		if(!inicializado || ejecutando){
    		return;
    		}
    		ejecutando = true;
    		thread = new Thread(this);
    		thread.start();
    
    	}	
    	
    	public void stop() throws Exception {
    		ejecutando = false;
    		if (thread != null) {
    			thread.join();
    			}
    	}
    	
    	public boolean isEjecutando(){
    		return ejecutando;
    		}	 
    	
    	public void send(String mensaje){
    		out.println(mensaje);
    	}
    	public void run(){
    		while (ejecutando){
    		try {
    			socket.setSoTimeout(2500);
    			String mensaje = in.readLine();
    			if (mensaje == null){
    				break;
    			}
    			System.out.println(
    				"Mensaje enviado por el servidor: " + mensaje);
    			
    			}
    			catch (SocketTimeoutException e){
    				}
    						       catch	(Exception e){
    						    	   System.out.println(e);
    						    	   break;
    						       	}				
    			}	
    		   close();
    	
    		}
    
    	
    	public static void main (String[] args) throws Exception {
    	System.out.println("Iniciando cliente...");
    	System.out.println("Iniciando conexión...");
    	Cliente cliente = new Cliente("localhost",2525);
    	System.out.println("Conexión establecida");
    	cliente.start();
    	
    	Scanner scanner = new Scanner(System.in);
    
    	while(true) {
    		System.out.print("Escriba su mensaje:");
    		String mensaje = scanner.nextLine();
    		if(!cliente.isEjecutando()){
    		break;		
    		}		
    
    
    		cliente.send(mensaje);
    		
    		if ("Fin".equals(mensaje)){
    			break;
    		}
    		
    	}
    		System.out.println("Cerrando cliente");
    		cliente.stop();
    	}
    }
    then what?? I have no clue how to be embeding this litle counter,(I dont know even where if in the server or the client)
    Code:
    import java.io.*;
    import java.util.*;
    public class CuentaPalabras
    	{
    		public static void main(String[] args) throws IOException
    		{
    			BufferedReader stdin =
    			new BufferedReader(new InputStreamReader(System.in), 1);
    			String line;
    			StringTokenizer palabras;
    			int contador = 0;
    			// AquÃ* se procesan las palabras hasta que se llega al fin Ctrl+z en guindows pero en unixes es Ctrl+d . Creo=)
    			while ((line = stdin.readLine()) != null)
    			{
    		// AquÃ* se cuentan las palabras.
    			palabras = new StringTokenizer(line);
    					while (palabras.hasMoreTokens())
    					{
    					palabras.nextToken();
    					contador++;
    					}
    				}
    			System.out.println("\n" + contador + " palabras leidas");
    		}
    	}
    this counter its supposed to count how many words are writen and then write a file back in the server/

    Thanks for any comment

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: socket saving file

    then what?? I have no clue how to be embeding this litle counter,(I dont know even where if in the server or the client)
    You'll need to describe exactly what problem you are trying to solve if you want us to be able to help you.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  3. #3
    Join Date
    May 2012
    Posts
    8

    Re: socket saving file

    Hi there , thanks for reading, In otherd words how (and where) can add a little rutine that allows to save from stdin into the server?

  4. #4
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: socket saving file

    That still doesn't really explain what you are trying to achieve, but assuming you mean save information entered by the client on the server then very basically you need some client side code to read from stdin, create a connection to the server and pass the input to the server. On the server side you need code to accept this data and save it to an appropriate file.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  5. #5
    Join Date
    May 2012
    Posts
    8

    Exclamation Re: socket saving file

    Quote Originally Posted by keang View Post
    That still doesn't really explain what you are trying to achieve, but assuming you mean save information entered by the client on the server then very basically you need some client side code to read from stdin, create a connection to the server and pass the input to the server. On the server side you need code to accept this data and save it to an appropriate file.
    Yeay!!! At least somebody could give me ideas

    (of course Im just 2 days ago beginning with java and Im a old C roamer so its messing my ideas)

  6. #6
    Join Date
    May 2012
    Posts
    8

    Re: socket saving file

    Client updated!!! well now it write down a file to be sended to the server (working in this right now!!!=)

    Code:
    ...
    	public static void main (String[] args) throws Exception {
    	System.out.println("Iniciando cliente...");
    	System.out.println("Iniciando conexi&#243;n...");
    	Cliente cliente = new Cliente("localhost",2525);
    	System.out.println("Conexi&#243;n establecida");
    	cliente.start();
    	
    	Scanner scanner = new Scanner(System.in);
    	
    	while(true) {
    		System.out.print("Escriba su mensaje:");
    		String mensaje = scanner.nextLine();
    		BufferedWriter out = new BufferedWriter(new FileWriter("cadenas"));
    		out.write(mensaje);
    		out.close();
    		if(!cliente.isEjecutando()){
    		break;		
    		}		
    
    
    		cliente.send(mensaje);
    		
    		if ("Fin".equals(mensaje)){
    			break;
    		}
    		
    	}
    		System.out.println("Cerrando cliente");
    		cliente.stop();
    	}
    }
    But the thing now its the file its writen cadenas(meaning strings) is created but it saves only the last thing writen when the server its not closed
    i.e. if I write down a line then this line its saved but the next one overwrite the one before and when closing the server all I got its the blank file

  7. #7
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: socket saving file

    Why are you saving the file on the client side, I thought you wanted to do that on the server side?

    but it saves only the last thing writen
    By default FileWriter opens an existing file in overwrite mode, if you want to append to it then use the 2 arg constructor which allows you to specify whether to use overwrite or append.

    BTW If you are writing several things to a file then the first thing to do is to open/create the file then repeatedly read from stdin and write to the file and finally, once all input is complete, close the file.

    Also, when dealing with streams always wrap the code is a try-catch-finally statement and put the stream close code in the finally clause so the stream is closed no matter how the code exits.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  8. #8
    Join Date
    May 2012
    Posts
    8

    Re: socket saving file

    i dunno understand how to write the buffered stream in the server, thats why I write in the client and then I attempt to send over to the server

  9. #9
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: socket saving file

    Why not just send the string you are reading in.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  10. #10
    Join Date
    May 2012
    Posts
    8

    Thumbs up Re: socket saving file

    Quote Originally Posted by keang View Post
    Why not just send the string you are reading in.
    Yeah really a better idea!!! this happens when you start throwing code without realizing what are you doing!!!
    In fact I already changed that on the server side.
    the last thing I must add its a authentication routine but I wonder how to do that!!!???

  11. #11
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: socket saving file

    the last thing I must add its a authentication routine but I wonder how to do that
    That really depends on what level of authentication you need. It can be as basic as the client just sending some raw data that identifies it (ie a name), as complex as the system requiring the client send encrypted data that has been verified and signed by a third party (such as SSL certificates) or somewhere in between.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  12. #12
    Join Date
    May 2012
    Posts
    8

    Re: socket saving file

    Im thinking of something based on the Class Authenticator, like the one showed in
    https://www.blackbaud.com/files/supp...entication.htm

    but What I dont understand its I must make a separated class file? and how call from server the auth method?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured