Fórum TCP/UDP #498834
23/10/2014
0
O servidor sorteia um num de 1 a 10 e responde o intervalo que o numero deve estar. O cliente envia outro numero dentro do novo intervalo. O servidor envia o novo
intervalo até o receba o numero sorteado. O servidor desfaz a conexão.
Fulero Santos
Curtir tópico
+ 0Post mais votado
30/10/2014
Server.java
// This example is from the book _Java in a Nutshell_ by David Flanagan.
// Written by David Flanagan. Copyright (c) 1996 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class Server extends Thread {
public final static int DEFAULT_PORT = 6789;
protected int port;
protected ServerSocket listen_socket;
// Exit with an error message, when an exception occurs.
public static void fail(Exception e, String msg) {
System.err.println(msg + ": " + e);
System.exit(1);
}
// Create a ServerSocket to listen for connections on; start the thread.
public Server(int port) {
if (port == 0) port = DEFAULT_PORT;
this.port = port;
try { listen_socket = new ServerSocket(port); }
catch (IOException e) { fail(e, "Exception creating server socket"); }
System.out.println("Server: listening on port " + port);
this.start();
}
// The body of the server thread. Loop forever, listening for and
// accepting connections from clients. For each connection,
// create a Connection object to handle communication through the
// new Socket.
public void run() {
try {
while(true) {
Socket client_socket = listen_socket.accept();
Connection c = new Connection(client_socket);
}
}
catch (IOException e) {
fail(e, "Exception while listening for connections");
}
}
// Start the server up, listening on an optionally specified port
public static void main(String[] args) {
int port = 0;
if (args.length == 1) {
try { port = Integer.parseInt(args[0]); }
catch (NumberFormatException e) { port = 0; }
}
new Server(port);
}
}
// This class is the thread that handles all communication with a client
class Connection extends Thread {
protected Socket client;
protected DataInputStream in;
protected PrintStream out;
// Initialize the streams and start the thread
public Connection(Socket client_socket) {
client = client_socket;
try {
in = new DataInputStream(client.getInputStream());
out = new PrintStream(client.getOutputStream());
}
catch (IOException e) {
try { client.close(); } catch (IOException e2) { ; }
System.err.println("Exception while getting socket streams: " + e);
return;
}
this.start();
}
private int sorteiaValor(){
Random random = new Random();
return random.nextInt(10);
}
// Provide the service.
// Read a line, reverse it, send it back.
public void run() {
String line;
try {
for(;;) {
// read in a line
line = in.readLine();
if (line == null){
out.println("Digite um número entre 1 e 10");
break;
}else{
int valorSorteado = sorteiaValor();
System.out.println("Valor sorteado = "+valorSorteado);
System.out.println("Valor digitado pelo usuário = "+line);
if (valorSorteado == Integer.parseInt(line)){
out.println("Parabéns, você acertou o valor. " +
"O programa será encerrado");
return;
}else{
out.println("O valor sorteado é diferente do digitado. Tente novamente");
}
}
}
}
catch (IOException e) { ; }
finally { try {client.close();} catch (IOException e2) {;} }
}
}
Ronaldo Lanhellas
Gostei + 1
Mais Posts
23/10/2014
Ronaldo Lanhellas
O servidor sorteia um num de 1 a 10 e responde o intervalo que o numero deve estar. O cliente envia outro numero dentro do novo intervalo. O servidor envia o novo
intervalo até o receba o numero sorteado. O servidor desfaz a conexão.
A ideia aqui é usar Socket para tal comunicação, veja : https://www.devmedia.com.br/sockets-com-java-parte-i/9465
Gostei + 0
23/10/2014
Fulero Santos
Gostei + 0
23/10/2014
Ronaldo Lanhellas
Gostei + 0
23/10/2014
Fulero Santos
Gostei + 0
23/10/2014
Eduardo Pessoa
Gostei + 0
23/10/2014
Fulero Santos
LINK PARA APLICACAO JAVA
Gostei + 0
23/10/2014
Fulero Santos
Gostei + 0
23/10/2014
Ronaldo Lanhellas
Então seu problema não é relacionado a comunicação, já que você já tem ela pronta, é o algoritmo de sorteio de números que está lhe complicando, vou pensar na solução e lhe ajudar.
Gostei + 0
27/10/2014
Fulero Santos
Gostei + 0
28/10/2014
Ronaldo Lanhellas
Gostei + 0
29/10/2014
Fulero Santos
Gostei + 0
06/11/2014
Luciano Chaves
Ronaldo, como ficaria a modificação na classe cliente?
Gostei + 0
07/11/2014
Luciano Chaves
Server.java
// This example is from the book _Java in a Nutshell_ by David Flanagan.
// Written by David Flanagan. Copyright (c) 1996 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class Server extends Thread {
public final static int DEFAULT_PORT = 6789;
protected int port;
protected ServerSocket listen_socket;
// Exit with an error message, when an exception occurs.
public static void fail(Exception e, String msg) {
System.err.println(msg + ": " + e);
System.exit(1);
}
// Create a ServerSocket to listen for connections on; start the thread.
public Server(int port) {
if (port == 0) port = DEFAULT_PORT;
this.port = port;
try { listen_socket = new ServerSocket(port); }
catch (IOException e) { fail(e, "Exception creating server socket"); }
System.out.println("Server: listening on port " + port);
this.start();
}
// The body of the server thread. Loop forever, listening for and
// accepting connections from clients. For each connection,
// create a Connection object to handle communication through the
// new Socket.
public void run() {
try {
while(true) {
Socket client_socket = listen_socket.accept();
Connection c = new Connection(client_socket);
}
}
catch (IOException e) {
fail(e, "Exception while listening for connections");
}
}
// Start the server up, listening on an optionally specified port
public static void main(String[] args) {
int port = 0;
if (args.length == 1) {
try { port = Integer.parseInt(args[0]); }
catch (NumberFormatException e) { port = 0; }
}
new Server(port);
}
}
// This class is the thread that handles all communication with a client
class Connection extends Thread {
protected Socket client;
protected DataInputStream in;
protected PrintStream out;
// Initialize the streams and start the thread
public Connection(Socket client_socket) {
client = client_socket;
try {
in = new DataInputStream(client.getInputStream());
out = new PrintStream(client.getOutputStream());
}
catch (IOException e) {
try { client.close(); } catch (IOException e2) { ; }
System.err.println("Exception while getting socket streams: " + e);
return;
}
this.start();
}
private int sorteiaValor(){
Random random = new Random();
return random.nextInt(10);
}
// Provide the service.
// Read a line, reverse it, send it back.
public void run() {
String line;
try {
for(;;) {
// read in a line
line = in.readLine();
if (line == null){
out.println("Digite um número entre 1 e 10");
break;
}else{
int valorSorteado = sorteiaValor();
System.out.println("Valor sorteado = "+valorSorteado);
System.out.println("Valor digitado pelo usuário = "+line);
if (valorSorteado == Integer.parseInt(line)){
out.println("Parabéns, você acertou o valor. " +
"O programa será encerrado");
return;
}else{
out.println("O valor sorteado é diferente do digitado. Tente novamente");
}
}
}
}
catch (IOException e) { ; }
finally { try {client.close();} catch (IOException e2) {;} }
}
}
Ronaldo, como ficaria a modificação na classe cliente?
Gostei + 0
07/11/2014
Ronaldo Lanhellas
Server.java
// This example is from the book _Java in a Nutshell_ by David Flanagan.
// Written by David Flanagan. Copyright (c) 1996 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class Server extends Thread {
public final static int DEFAULT_PORT = 6789;
protected int port;
protected ServerSocket listen_socket;
// Exit with an error message, when an exception occurs.
public static void fail(Exception e, String msg) {
System.err.println(msg + ": " + e);
System.exit(1);
}
// Create a ServerSocket to listen for connections on; start the thread.
public Server(int port) {
if (port == 0) port = DEFAULT_PORT;
this.port = port;
try { listen_socket = new ServerSocket(port); }
catch (IOException e) { fail(e, "Exception creating server socket"); }
System.out.println("Server: listening on port " + port);
this.start();
}
// The body of the server thread. Loop forever, listening for and
// accepting connections from clients. For each connection,
// create a Connection object to handle communication through the
// new Socket.
public void run() {
try {
while(true) {
Socket client_socket = listen_socket.accept();
Connection c = new Connection(client_socket);
}
}
catch (IOException e) {
fail(e, "Exception while listening for connections");
}
}
// Start the server up, listening on an optionally specified port
public static void main(String[] args) {
int port = 0;
if (args.length == 1) {
try { port = Integer.parseInt(args[0]); }
catch (NumberFormatException e) { port = 0; }
}
new Server(port);
}
}
// This class is the thread that handles all communication with a client
class Connection extends Thread {
protected Socket client;
protected DataInputStream in;
protected PrintStream out;
// Initialize the streams and start the thread
public Connection(Socket client_socket) {
client = client_socket;
try {
in = new DataInputStream(client.getInputStream());
out = new PrintStream(client.getOutputStream());
}
catch (IOException e) {
try { client.close(); } catch (IOException e2) { ; }
System.err.println("Exception while getting socket streams: " + e);
return;
}
this.start();
}
private int sorteiaValor(){
Random random = new Random();
return random.nextInt(10);
}
// Provide the service.
// Read a line, reverse it, send it back.
public void run() {
String line;
try {
for(;;) {
// read in a line
line = in.readLine();
if (line == null){
out.println("Digite um número entre 1 e 10");
break;
}else{
int valorSorteado = sorteiaValor();
System.out.println("Valor sorteado = "+valorSorteado);
System.out.println("Valor digitado pelo usuário = "+line);
if (valorSorteado == Integer.parseInt(line)){
out.println("Parabéns, você acertou o valor. " +
"O programa será encerrado");
return;
}else{
out.println("O valor sorteado é diferente do digitado. Tente novamente");
}
}
}
}
catch (IOException e) { ; }
finally { try {client.close();} catch (IOException e2) {;} }
}
}
Ronaldo, como ficaria a modificação na classe cliente?
Na classe cliente não mude nada, pois é apenas o servidor que vai cuidar do sorteio e o restante da lógica, a classe cliente apenas continua enviando o valor como já estava fazendo antes.
Gostei + 0
07/11/2014
Luciano Chaves
Server.java
// This example is from the book _Java in a Nutshell_ by David Flanagan.
// Written by David Flanagan. Copyright (c) 1996 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class Server extends Thread {
public final static int DEFAULT_PORT = 6789;
protected int port;
protected ServerSocket listen_socket;
// Exit with an error message, when an exception occurs.
public static void fail(Exception e, String msg) {
System.err.println(msg + ": " + e);
System.exit(1);
}
// Create a ServerSocket to listen for connections on; start the thread.
public Server(int port) {
if (port == 0) port = DEFAULT_PORT;
this.port = port;
try { listen_socket = new ServerSocket(port); }
catch (IOException e) { fail(e, "Exception creating server socket"); }
System.out.println("Server: listening on port " + port);
this.start();
}
// The body of the server thread. Loop forever, listening for and
// accepting connections from clients. For each connection,
// create a Connection object to handle communication through the
// new Socket.
public void run() {
try {
while(true) {
Socket client_socket = listen_socket.accept();
Connection c = new Connection(client_socket);
}
}
catch (IOException e) {
fail(e, "Exception while listening for connections");
}
}
// Start the server up, listening on an optionally specified port
public static void main(String[] args) {
int port = 0;
if (args.length == 1) {
try { port = Integer.parseInt(args[0]); }
catch (NumberFormatException e) { port = 0; }
}
new Server(port);
}
}
// This class is the thread that handles all communication with a client
class Connection extends Thread {
protected Socket client;
protected DataInputStream in;
protected PrintStream out;
// Initialize the streams and start the thread
public Connection(Socket client_socket) {
client = client_socket;
try {
in = new DataInputStream(client.getInputStream());
out = new PrintStream(client.getOutputStream());
}
catch (IOException e) {
try { client.close(); } catch (IOException e2) { ; }
System.err.println("Exception while getting socket streams: " + e);
return;
}
this.start();
}
private int sorteiaValor(){
Random random = new Random();
return random.nextInt(10);
}
// Provide the service.
// Read a line, reverse it, send it back.
public void run() {
String line;
try {
for(;;) {
// read in a line
line = in.readLine();
if (line == null){
out.println("Digite um número entre 1 e 10");
break;
}else{
int valorSorteado = sorteiaValor();
System.out.println("Valor sorteado = "+valorSorteado);
System.out.println("Valor digitado pelo usuário = "+line);
if (valorSorteado == Integer.parseInt(line)){
out.println("Parabéns, você acertou o valor. " +
"O programa será encerrado");
return;
}else{
out.println("O valor sorteado é diferente do digitado. Tente novamente");
}
}
}
}
catch (IOException e) { ; }
finally { try {client.close();} catch (IOException e2) {;} }
}
}
Ronaldo, como ficaria a modificação na classe cliente?
Na classe cliente não mude nada, pois é apenas o servidor que vai cuidar do sorteio e o restante da lógica, a classe cliente apenas continua enviando o valor como já estava fazendo antes.
Boa tarde, Ronaldo!
Eu estou executando os dois pelo NetBeans, primeiro o server e depois o cliente.
Após executar o server aparece:
run:
Server: listening on port 6789
Ao executar o cliente, aparece:
run:
Usage: java Client <hostname> [<port>]
CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)
Não era pra haver uma conexão entre os dois com envio e recebimento de mensagens?
O cliente não me dá opções de digitar nada e no servidor, se eu digito um número qualquer, nada acontece.
O que há de errado?
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)