Código servidor cliente

4 respostas
J

Boa tarde, tenho o código de um servidor e de um cliente que acessa esse servidor, só que o codigo do servidora ta com um erro na hora de compila, o erro acontece na linha numero 34, vou postar aqui o codigo do server, pra ver se alguem consegue me ajudar, desde ja agradeço, obrigado

import java.io.*;
import java.net.*;
 
public class MyServer3 extends Thread {
	private ServerSocket sock;
 
	public MyServer3(int port) {
		super();
		try {
			sock = new ServerSocket(port);
			System.out.println("MyServer running at port " + port);
		} catch (IOException e) {
			System.out.println("Error: couldn't create socket.");
			System.exit(1);
		}
	}
 
	public void run() {
		Socket client = null;
 
		while (true) {
			if (sock == null)
				return;
			try {
				client = sock.accept();
				// Recebendo identificacao
				BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
				String c = in.readLine();
				System.out.println(c);
				
				// Enviando Informacoes
				BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
				PrintWriter os = new PrintWriter(bos, false);
				os.println(executar(c));
				os.flush();
				os.close();
				client.close();
			} catch (IOException e) {
				System.out.println("Error: couldn't connect to client.");
				System.exit(1);
			}
		}
	}
	
	public String executar (int x) {
		int fat,aux;
		aux=x;
		fat=1;
		while (aux>1){
			fat = fat*(aux);
			aux--;
		} 
		return ("O fatorial de "+x+" é: "+fat); 
	}
	 
	public static void main(String[] arguments) {
		int port = 4000;
		if (arguments.length == 1) {
			port = Integer.parseInt(arguments[0]);
		}
		MyServer3 server = new MyServer3(port);
		server.start();
	}
}

4 Respostas

ViniGodoy

O parâmetro da função executar é do tipo int, no entanto, a variável c é do tipo String.

J

Da um erro assim:

MyServer3.java:34: error: method executar in class MyServer3 cannot be applied t

o given types;

os.println(executar©);

^

required: int

found: String

reason: actual argument String cannot be converted to int by method invocation

conversion

1 error

suspeito que seja alguma coisa na minha função do fatorial

ViniGodoy
Não, o problema foi o que eu falei. E a mensagem de erro é bem clara

Sua função pede int (required)

Mas você está passando um String (found)

Ou você tenta fazer o parse dessa String para int (com Integer.parseInt), ou não vai rolar…

J

Sim, eu vi um topico no proprio guj sobre isso e tentei fazer, tanto dentro da função quanto fora dela, dentro da função run do codigo, mas nao rolo de nenhum desses dois jeitos e nao consigo ver um terceiro jeito de fazer isso.

Criado 6 de abril de 2013
Ultima resposta 7 de abr. de 2013
Respostas 4
Participantes 2