I have found an example of a simple program in java that suppose to work which implements a client-server example in Java.
Client code:
import java.io.*;
import java.net.*;
public class ClientDemo {
public static void main(String[] args) {
try {
Socket sock = new Socket ("127.0.0.1", 4321);
DataInputStream input = new DataInputStream(sock.getInputStream());
boolean more_data = true;
while (more_data) {
String line = input.readLine();
if(line==null) {
more_data = false;
}
else {
System.out.println(line);
}
}
}
catch (IOException e) {
}
}
}
Server code:
import java.io.*;
import java.net.*;
public class SimpleServer
{
public static void main(String[] args)
{
try
{
ServerSocket server = new ServerSocket (4321);
Socket sock = server.accept();
DataInputStream inp = new DataInputStream (sock.getInputStream());
PrintStream out = new PrintStream (sock.getOutputStream());
output.println("server message");
output.println("QUIT to Quit");
boolean more_data = true;
while (more_data)
{
String line = inp.readLine();
if(line==null)
{
more_data = false;
}
else
{
output.println("Server:" +line+"\n");
if(line.trim().equals("Exit")
{
more_data = false;
}
}
}
sock.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
when running the server first and then the client, I get the welcome message, but when entering a text in the client console then pressing enter, nothing happens.
I tried replacing the DataInputStream in BufferedInputStream as in the docs it said readline was deprecated, but the same behavior, plus I tried to change to scanner object, with nextLine, bt the same behavior there too.
your input would be appreciated very much.