this are my first java steps with a socket connection. I like to code a tcp client that connects to a server and read all data that the server will ever send. Each message from the server will be terminated by 0x00.
First question: How can i read this variable message length?
Secont question: if the user enters text via the keyboard this text should be send to the server, while i am receiving. But how can i send data while i am reading from the server?
This is my code till now:
import java.io.*;
public class Client {
public static void main(String[] args) {
Client client = new Client();
try {
client.test();
} catch (IOException e) {
e.printStackTrace();
}
}
void test() throws IOException {
String ip = "127.0.0.1"; // localhost
int port = 12345;
java.net.Socket socket = new java.net.Socket(ip,port); // verbindet sich mit Server
String zuSendendeNachricht = "Hello World0x00";
schreibeNachricht(socket, zuSendendeNachricht);
while (true){
String empfangeneNachricht = leseNachricht(socket);
System.out.println(empfangeneNachricht);
}
}
void schreibeNachricht(java.net.Socket socket, String nachricht) throws IOException {
PrintWriter printWriter =
new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()));
printWriter.print(nachricht);
printWriter.flush();
}
String leseNachricht(java.net.Socket socket) throws IOException {
BufferedReader bufferedReader =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
char[] buffer = new char[200];
int anzahlZeichen = bufferedReader.read(buffer, 0, 200); // blockiert bis Nachricht empfangen
String nachricht = new String(buffer, 0, anzahlZeichen);
System.out.println(nachricht);
}
}
And how can i read a variable message length