LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Problem with simple Java network program (https://www.linuxquestions.org/questions/programming-9/problem-with-simple-java-network-program-4175526408/)

kedarp 11-24-2014 10:30 PM

Problem with simple Java network program
 
Hello,
I was just trying a simple program to get reply from the Server. I need some help with it.

Here is the Server code -
Code:

package simpleprograms;

import java.net.Socket;
import java.net.ServerSocket;
import java.io.PrintWriter;

public class ListeningServer {

    public static void main(String[] args) {
        try {
            //InetSocketAddress addr=new InetSocketAddress(7);
            ServerSocket servsock = new ServerSocket(7800);
            Socket sock;
            PrintWriter pw;
           
            if(servsock.isBound()) {
                System.out.println("Server at " + servsock.getInetAddress() +
                        " is listening on port " + servsock.getLocalPort());
            }
            else {
                System.out.println("Bind Error");
                //exit(1);
            }
            while (true) {
                sock = servsock.accept();
                pw=new PrintWriter(sock.getOutputStream());
                pw.println("Hello");
                sock.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Here is the client program -
Code:

package simpleprograms;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class PingServer {

    public static void main(String[] args) {
        try {
            Socket t = new Socket("127.0.0.1", 7800);
            DataInputStream dis = new DataInputStream(t.getInputStream());
            byte[] b = new byte[1024];

            dis.read(b);
            String str = new String(b);
            System.out.println(str);
            if (str.equals("Hello")) {
                System.out.println("Alive");
            } else {
                System.out.println("Dead");
            }
            t.close();
        }
        catch(UnknownHostException ex) {
            System.out.println(ex.toString());
        }
        catch(IOException ex) {
            System.out.println(ex.toString());
        }
        catch (Exception ex) {
            //System.out.println(ex.toString());
            ex.toString();
        }
    }
}

When I run the Server and the Client, I get the O/P from the Server as -
Dead

jlliagre 11-25-2014 03:27 PM

There is at least a couple of bugs in this code.

The server fails to flush its output and the client test is wrong..


All times are GMT -5. The time now is 03:46 AM.