I'm starting in java and I have a problem with sockets, I wanted my server to receive a value and then I wanted to turn it into a String
so I could include it in if
conditions. However, despite the server receiving the text without problem, I can not pass the value to a String
.
Follow the server code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javasockets;
import java.io.DataInputStream;
import java.io.IOException;
import static java.lang.System.exit;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
*
* @author Nuno
*/
public class JavaSockets {
public static String T = "s";
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
try {
ServerSocket sckServer = new ServerSocket(5000);
System.out.println("Porta 5000 aberta!");
Socket sck;
while (true) {
sck = sckServer.accept();
try (Scanner entrada = new Scanner(sck.getInputStream())) {
while (entrada.hasNextLine()) {
System.out.println(entrada.nextLine());
}
String texto = entrada.nextLine();
System.out.println("ola" + texto);
String fnames = texto;
System.out.println("ola" + fnames);
System.out.println(texto);
if (texto.equals(T)) {
System.out.println("LOOL");
}
}
sckServer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The following is the client code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javasockets;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Nuno
*/
public class cliente {
public static void main(String[] args) throws IOException {
while (true) {
Socket cliente = new Socket("127.0.0.1", 5000);
System.out.println("O cliente se conectou ao servidor!");
Scanner teclado = new Scanner(System.in);
PrintStream saida = new PrintStream(cliente.getOutputStream());
while (teclado.hasNextLine()) {
saida.println(teclado.nextLine());
}
saida.flush();
saida.close();
teclado.close();
}
}
static Object getInetAddress() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}