Results 1 to 9 of 9
Thread: socket server moded
- 06-01-2012, 06:08 AM #1
Member
- Join Date
- May 2012
- Posts
- 9
- Rep Power
- 0
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]
heres the class that supports the serverJava 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" ); } }
and heres the clientJava 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(); } }
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: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(); } }
this counter its supposed to count how many words are writen and then write a file back in the server/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"); } }
Thanks for any comment
- 06-01-2012, 08:29 PM #2
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.
Where are the words being written?supposed to count how many words are writen
That sounds lke the client is to send a file to the server. What is in the file?write a file back in the server
When is the file supposed to be sent?If you don't understand my response, don't ignore it, ask a question.
- 06-01-2012, 09:00 PM #3
Member
- Join Date
- May 2012
- Posts
- 9
- Rep Power
- 0
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!!!.gif)
- 06-01-2012, 09:16 PM #4
Re: socket server moded
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.local file its send over the net. How can I do that?If you don't understand my response, don't ignore it, ask a question.
- 06-01-2012, 10:02 PM #5
Member
- Join Date
- May 2012
- Posts
- 9
- Rep Power
- 0
Re: socket server moded
Client updated!!! well now it write down a file to be sended to the server (working in this right now!!!=)
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 closedJava 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(); } }
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
- 06-01-2012, 10:36 PM #6
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.
If you don't understand my response, don't ignore it, ask a question.
- 06-02-2012, 07:18 PM #7
Member
- Join Date
- May 2012
- Posts
- 9
- Rep Power
- 0
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 linethe compiler says that mensaje is not resolved for Buffered... its like a mismatch between variable tipes.Java Code:[I]out.println(mensaje);[/I]
.gif)
.gif)
.gif)






- 06-02-2012, 07:25 PM #8
Re: socket server moded
Please post the full text of the error message.compiler says that mensaje is not resolved
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 accessedIf you don't understand my response, don't ignore it, ask a question.
- 06-02-2012, 08:41 PM #9
Member
- Join Date
- May 2012
- Posts
- 9
- Rep Power
- 0
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
-
Obfuscating Moded .jars
By _PB in forum Advanced JavaReplies: 4Last Post: 10-29-2011, 12:07 PM -
Socket HTTP-Server
By MichaelH in forum NetworkingReplies: 6Last Post: 05-06-2011, 08:45 PM -
events on a server socket
By newbiejava in forum New To JavaReplies: 13Last Post: 08-03-2010, 08:24 AM -
Server Socket
By Moncleared in forum New To JavaReplies: 1Last Post: 09-05-2009, 06:08 AM


5Likes
LinkBack URL
About LinkBacks

Bookmarks