Java - Servidor Java

 
Vista:

Servidor Java

Publicado por Lidayer (30 intervenciones) el 19/09/2008 12:16:25
Hola,alguien me podria echar un cable para realizar un servidor que guarde en un fichero de texto todo lo que reciba desde un cliente.
Gracias.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:Servidor Java

Publicado por Gilberto (378 intervenciones) el 21/09/2008 04:24:54
import java.net.*;

class Servidor implements Runnable {

private ServerSocket ss;
private Thread thread;
int nc;

Servidor(int puerto) {
try{
ss = new ServerSocket(puerto);
nc = 0;
thread = new Thread(this,"servidor");
thread.start();
System.out.println("Servidor listo");
}catch(Exception e) {
e.printStackTrace();
}
}

public void run() {
while(true) {
try{
new Conexion(ss.accept(),++nc);
}catch(Exception e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
new Servidor(200);
}
}

class Conexion implements Runnable {

private Socket socket;
private Thread thread;
private BufferedReader br;
private PrintWriter pw;
private File file;

Conexion(Socket s,int n) {
try{
socket = s;
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
file = new File("Cliente"+n);
pw = new PrintWriter(new FileWriter(file));
thread = new Thread(this,"Conexion"+n);
thread.start();
System.out.println("Nueva conéxion lista");
}catch(Exception e) {
e.printStackTrace();
}
}

public void run() {
try{
while(socket.isConnected()) {
String s = br.readLine();
System.out.println(s);
pw.println(s);
pw.flush();
}
br.close();
pw.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}

public class Cliente implements Runnable {

private Socket socket;
private PrintWriter pw;
private BufferedReader br;
private Thread thread;

public Cliente() {
try{
socket = new Socket("localhost",200);
pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
br = new BufferedReader(new InputStreamReader(System.in));
thread = new Thread(this);
thread.start();
}catch(Exception e) {
e.printStackTrace();
}
}

public void run() {
while(true) {
try{
pw.println(br.readLine());
}catch(Exception e) {
e.printStackTrace();
}
}
}

/**
* Method main
*
*
* @param args
*
*/
public static void main(String[] args) {
// TODO: Add your code here
new Cliente();
}
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:Servidor Java

Publicado por Lidayer (30 intervenciones) el 23/09/2008 17:38:35
Gracias por contestar.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar