Sockets

4 respostas
L

Estou precisando de ajuda.
Tenho que fazer uma aplicação utilizando sockets com as seguintes características:

Escrever uma aplicação usando socket em Java
para que toda vez que um cliente conectar no
servidor, o servidor fornecer uma mensagem para o
cliente (aleatória e diferente como um “biscoito chines”).

Aguardo resposta urgente.

Lara
:?:

4 Respostas

ecarmo

Lara,

De uma olhada neste tutorial do guj http://www.guj.com.br/user.article.get.chain?page=1&article.id=126

Vai lhe ajudar muito

C

A seguir um exemplo para sua aplicação:

O servidor:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MeuServerSocket {
    public static void main(String[] args) {
		MeuServerSocket o = new MeuServerSocket();
		o.go();
    }
    private void go() {
		Thread t = new Thread(new ServerRunner());
		t.start();        
    }
    class ServerRunner implements Runnable {
		ServerSocket s;
        public void run() {
            try {
                s = new ServerSocket(4321);
                while (true) {
                	Socket sock = s.accept();
                	Thread t = new Thread(new ServerProcessor(sock));
                	t.start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    class ServerProcessor implements Runnable {
    	private Socket s;
		ServerProcessor(Socket sock) {
			s = sock;
		}
        public void run() {
            try {
                s.getOutputStream().write(getMessage().getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    	private String getMessage() {
    		String s = (long)(Math.random()*10000000) + "               ";
    		return s.substring(0, 10);
    	}
    }
}

O client:

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class MeuClientSocket {
    public static void main(String[] args) throws IOException {
    	InetAddress ina;
        ina = InetAddress.getLocalHost();
    	Socket s = new Socket(ina, 4321);
    	byte[] b = new byte[10];
    	s.getInputStream().read(b);
    	s.close();
    	System.out.println("Meu numero da sorte é:" + new String(b));
    }
}
dukejeffrie

que vergonha, postar o dever de casa no GUJ…

Sombriks

putz, eu quase entendi, ehehehe… eu gosti pq parece simples, mas vcs poderiam colocar mais exemplos aki? (o último foi bem elegante, tinha até classes internas…)
e como eu poderia aplicar isso a um sistema P2P? é possível? se for, por favor, ajudem um pobre estudante lammer…

Criado 6 de maio de 2004
Ultima resposta 15 de abr. de 2005
Respostas 4
Participantes 5