Results 1 to 9 of 9
Like Tree5Likes
  • 1 Post By Norm
  • 1 Post By Norm
  • 2 Post By Norm
  • 1 Post By Norm

Thread: socket server moded

  1. #1
    isamu01 is offline Member
    Join Date
    May 2012
    Posts
    9
    Rep Power
    0

    Thumbs up socket server moded

    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]
    Java 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
    Java 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
    Java 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)
    Java 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
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,332
    Rep Power
    25

    Default Re: socket server moded

    Also posted at Socket saving file - Dev Shed

    You've posted a lot of code. Did you write any of it or did you copy it from somewhere? Before making changes to the code, you need to study what it does and where in the code you need to add the new code that is to do the counting.

    supposed to count how many words are writen
    Where are the words being written?

    write a file back in the server
    That sounds lke the client is to send a file to the server. What is in the file?
    When is the file supposed to be sent?
    isamu01 likes this.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    isamu01 is offline Member
    Join Date
    May 2012
    Posts
    9
    Rep Power
    0

    Default Re: socket server moded

    [QUOTE=Norm;288926]Also posted at Socket saving file - Dev Shed

    Did you write any of it or did you copy it from somewhere?

    Nah!!! if what Im looking for is writen there over the net I wouldnt be posting bro!!!
    But I can say I just begin with java 2 days ago and Its dizzing me because im too used to c.
    The words are suppposed to be writen from user input thats why I use stdin. So the write back its what I dont understand
    lets imagine I write this in the client and the local file its send over the net. How can I do that?
    or instead, the stream its directly send to the server Im too ignorant in java to see can do this!!!
    Thanks for reading!!!

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,332
    Rep Power
    25

    Default Re: socket server moded

    local file its send over the net. How can I do that?
    Open the file with a class like FileInputStream or FileReader depending on the file's contents, read the bytes/characters from the file and write the bytes/characters on the connection to the program on the other end of the connection. That program will have to read what is sent and write it to a file.
    isamu01 likes this.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    isamu01 is offline Member
    Join Date
    May 2012
    Posts
    9
    Rep Power
    0

    Default Re: socket server moded

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

    Java Code:
    ...
    	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();
    	[B][I]	BufferedWriter out = new BufferedWriter(new FileWriter("cadenas"));
    		out.write(mensaje);
    		out.close();[/I][/B]
    		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


    thanks Norm for taking your time and give a reading... Im working in the transmission problem roght now=p

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,332
    Rep Power
    25

    Default Re: socket server moded

    If you create a new version of the file every time you write to the file, there will only be one line in the file. Create the file one time before writing to it, write to it many times and then close the file when done writing to it.
    DarrylBurke and isamu01 like this.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    isamu01 is offline Member
    Join Date
    May 2012
    Posts
    9
    Rep Power
    0

    Thumbs up Re: socket server moded

    Yop! there Ive made my mind up ! and realize that the stream needed to be saved can be done on the server side, so Im changing again the code and updating Atendante.java where the stream received its passed to a file.


    Java Code:
    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);
    		[I]out.println(mensaje);[/I]
    	[B]	BufferedWriter out = new BufferedWriter(new FileWriter("cadenas",true));
    		out.write(mensaje);
    		out.close();[/B]
    		
    		if ("Fin".equals(mensaje)) {
    									break;
    									}
    				
    		}
    		catch (SocketTimeoutException e){
    
    		}
    		catch (Exception e){
    			System.out.println(e);
    			break;
    		}
    			
    	}
    	System.out.println("Cerrando conexión");
    	close();
    
    	}

    two more questions, how can add a authentication routine and with the line
    Java Code:
    	[I]out.println(mensaje);[/I]
    the compiler says that mensaje is not resolved for Buffered... its like a mismatch between variable tipes.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,332
    Rep Power
    25

    Default Re: socket server moded

    compiler says that mensaje is not resolved
    Please post the full text of the error message.
    Is the variable: mensaje in scope (defined within same pair of {}s) where you are trying to access it?
    Move its definition to be within the same {}s as where it is being accessed
    isamu01 likes this.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    isamu01 is offline Member
    Join Date
    May 2012
    Posts
    9
    Rep Power
    0

    Default Re: socket server moded

    Roger that checked and corrected it was a location problem within the code. Now Im looking to use a basic authentication method like the one used in https://www.blackbaud.com/files/supp...entication.htm

    what I dont know is if a make a separata class file for the authentication or write inside the server/atendant file?

Similar Threads

  1. Obfuscating Moded .jars
    By _PB in forum Advanced Java
    Replies: 4
    Last Post: 10-29-2011, 12:07 PM
  2. Socket HTTP-Server
    By MichaelH in forum Networking
    Replies: 6
    Last Post: 05-06-2011, 08:45 PM
  3. events on a server socket
    By newbiejava in forum New To Java
    Replies: 13
    Last Post: 08-03-2010, 08:24 AM
  4. Server Socket
    By Moncleared in forum New To Java
    Replies: 1
    Last Post: 09-05-2009, 06:08 AM

Tags for this Thread

Posting Permissions

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