Olá gente,
desculpem incomodar, mas não sei se estou fazendo a pergunta no local correto do forum, mas vamos lá: estou tentando desenvolver uma aplicação que contenha um servidor e um cliente. Neste caso eu já fiz várias classes que simulam basicamente um jogo de futsal, e gostaria de tornar o meu cliente um time.
Para isso eu desenvolvi um código bem básico para tentar fazer a comunicação cliente servidor, mas mesmo assim não estou conseguindo fazer com que esse simples exemplo funcione… Eu já pesquisei bastante na net e tento adaptar o código mas mesmo assim não consegui… Desculpem caso o erro for meio bobo…
Segue o código do Cliente:
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.String;
class Client extends Thread {
private Socket socket;
private Scanner dataIn;
private PrintStream dataOut;
public Client(Socket socket) {
this.socket = socket;
try{
this.dataIn = new Scanner(socket.getInputStream());
this.dataOut = new PrintStream(socket.getOutputStream());
} catch (java.io.IOException e){}
}
public void run() {
try {
dataOut.println("Ola");
String resposta = dataIn.nextLine();
System.out.println(resposta);
} catch (Exception e){}
try {
socket.close();
} catch (Exception e) { System.out.println("A problem was observed while closing the connection");}
}
public static void main(String args[]) {
int port = 4893;
String host = "127.0.0.1";
try{
Socket client = new Socket(host, port);
} catch(UnknownHostException e){System.out.println("UnknownHostException");}
catch(IOException e){System.out.println("IOException");}
}
}
Agora o código do servidor:
import java.io.*;
import java.net.*;
import java.util.*;
public class MyWebServer extends Thread {
private ServerSocket server;
private Scanner dataIn;
private Scanner dataOut;
public MyWebServer(int port) throws IOException {
this.server = new ServerSocket(port);
}
public void run() {
Client threadClient;
try {
System.out.println("Waiting...");
while (true) {
Socket socketClient = this.server.accept();
threadClient = new Client(socketClient);
threadClient.start();
Scanner dataIn = new Scanner(socketClient.getInputStream());
PrintStream dataOut = new PrintStream(socketClient.getOutputStream());
String entrada = dataIn.nextLine();
System.out.println(entrada);
dataOut.println(entrada);
}
} catch (Exception e) { System.out.println("Problemas..."); }
}
public static void main(String args[]) {
int port = 4893;
try {
MyWebServer webServer = new MyWebServer(port);
webServer.start();
} catch (IOException e) { System.out.println("You do not have the necessary access to this computer to create a server."); }
}
}