-1

I am writing a server-client chat program.

Here is my code

SERVER:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HelloServer {

    public final static int defaultPort = 2345;

    public static void main(String[] args) {
        int port = defaultPort;
        try {
            port = Integer.parseInt(args[0]);
        } catch (Exception e) {
        }
        if (port <= 0 || port >= 65536) {
            port = defaultPort;
        }
        try {
            ServerSocket ss = new ServerSocket(port);

            while (true) {
                try {
                    Socket s = ss.accept();

                    String response = "Hello " + s.getInetAddress() + " on port " + s.getPort()
                            + "\r\n";
                    response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort()
                            + "\r\n";
                    OutputStream out = s.getOutputStream();
                    out.write(response.getBytes());
                    System.out.write(response.getBytes());
                    InputStream in = s.getInputStream();

                    System.out.println("from client");
                    int z = 0;
                    while ((z = in.read()) != -1) {
                        System.out.write(z);
                    }

                } catch (IOException e) {
                }
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

CLIENT:

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketGetINetAdd {

    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket socket = new Socket("192.xxx.x.xxx", 2345);
        InetAddress inetAddress = socket.getInetAddress();

        System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: "
                + socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
        BufferedInputStream bfINPUT = new BufferedInputStream(socket.getInputStream());
        int b = 0;
        OutputStream os = System.out;
        while ((b = bfINPUT.read()) != -1) {
            os.write(b);
        }
        OutputStream osNew = socket.getOutputStream();
        String s = "This Is The Client"; // data to be sent
        osNew.write(s.getBytes());
        os.write(s.getBytes());

}

I've connected them through my program.

But now I want to know How to send some data back to the server from client?

What would be the code for client(for sending data to server) and also the code for the server for showing the data received from the client on the console(server)?

P.S- I am a novice in network programming. Please do not criticize my coding style :P

Braj
  • 46,415
  • 5
  • 60
  • 76
arindrajit
  • 76
  • 1
  • 7
  • Do you expect us to write code for you? What have you tried? What is not working? – enterbios Apr 05 '14 at 13:03
  • 1
    That's a very broad question. SO can help you with a particular problem you are facing. If you want to learn network programming, stick to one of gazillion tutorials on the web. For example: [Oracle](http://docs.oracle.com/javase/tutorial/networking/sockets/), [JavaWorld](http://www.javaworld.com/article/2077322/core-java/sockets-programming-in-java-a-tutorial.html) to name only two. – Fildor Apr 05 '14 at 13:04
  • @enterbios=Do not vote a question down for insane reasons.I have mentioned that I could not write the code for sending data to the server from client. I want to learn the code coz I couldn't find it elsewhere. – arindrajit Apr 05 '14 at 13:07

2 Answers2

6

Use server stream

OutputStream os = socket.getOutputStream();

instead of client console output stream

OutputStream os = System.out;

at client side to write back to server.


and at server side use client stream to read from client in the same manner.

InputStream in = s.getInputStream();

I have already posted a sample code on server-client communication. Read it for your learning.

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • What next? are you getting any problem. I have mentioned some links in my post for better understanding. Please have a look. – Braj Apr 05 '14 at 13:16
  • I have posted a lots of samples on client-server communication. Please read it first. You will find your solution. – Braj Apr 05 '14 at 13:18
  • I have edited my program. I have used some of the techniques that you asked me to. But still there is no output of the data sent by the client on the server console. :( help me please. – arindrajit Apr 05 '14 at 13:25
  • @brij I have re-written the program and appended the code you asked me to. But there is no output on he server console. – arindrajit Apr 05 '14 at 13:29
  • Let me check. I will come back. – Braj Apr 05 '14 at 13:34
  • I have updated it your question itself. Check client side code. – Braj Apr 05 '14 at 13:38
  • Still you are using `System.out`. – Braj Apr 05 '14 at 13:38
  • @brij = I am trying to send "This is the client" string from client to the server.But it appears to me that you have commented out that. I want to send this from the client to the server. Is my question clear to you sir? You should just ignore the System.out part.That is nothing to be concerned about. I have used system.out on client coz I wanted to print the data from the client on the client's console for debugging purposes. – arindrajit Apr 05 '14 at 14:00
  • @brij- are you there sir? – arindrajit Apr 05 '14 at 14:00
  • No I am not sir. The problem is with `while ((b = bfINPUT.read()) != -1) {` that waits for next input from server. and any statements written below this `while` loop will not work. – Braj Apr 05 '14 at 14:18
0

You need threads. The client in this examples read the lines from the System.in and sends the line to the server. The server sends an echo.

In your real application you have to take a look of the encoding

Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HelloServer {

    public final static int defaultPort = 2345;

    public static void main(String[] args) {
        int port = defaultPort;
        try {
            port = Integer.parseInt(args[0]);
        } catch (Exception e) {
        }
        if (port <= 0 || port >= 65536) {
            port = defaultPort;
        }
        try {
            ServerSocket ss = new ServerSocket(port);

            while (true) {
                try {
                    Socket s = ss.accept();

                    new SocketThread(s).start();
                } catch (IOException e) {
                }
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }

    public static class SocketThread extends Thread {

        private Socket s;

        public SocketThread(Socket s) {
            this.s = s;
        }

        @Override
        public void run() {
            try {
                String response = "Hello " + s.getInetAddress() + " on port "
                        + s.getPort() + "\r\n";
                response += "This is " + s.getLocalAddress() + " on port "
                        + s.getLocalPort() + "\r\n";
                OutputStream out = s.getOutputStream();
                out.write(response.getBytes());
                BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                while (true) {
                    String line = input.readLine();
                    System.out.println("IN: " + line);
                    s.getOutputStream().write(("ECHO " + line + "\n").getBytes());
                    s.getOutputStream().flush();
                    System.out.println(line);
                }
            } catch (IOException e) {
                System.err.println(e);
            }
        }

    }
}

Client

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketGetINetAdd {


    public static void main(String[] args) throws UnknownHostException, IOException {
        Socket socket = new Socket("localhost", 2345);
        InetAddress inetAddress = socket.getInetAddress();

        System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: " + socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
        new OutputThread(socket.getInputStream()).start();

        InputStreamReader consoleReader = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(consoleReader);
        while (true) {                        
            String inline = in.readLine();
            if (inline.equals("by")) {
                break;
            }
            inline += "\n";
            socket.getOutputStream().write(inline.getBytes());
            socket.getOutputStream().flush();
        }
    }

    public static class OutputThread extends Thread {

        private InputStream inputstream;

        public OutputThread(InputStream inputstream) {
            this.inputstream = inputstream;
        }

        @Override
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
            while (true) {
                try {
                    String line = input.readLine();
                    System.out.println(line);
                } catch (IOException exception) {
                    exception.printStackTrace();
                    break;
                }
            }
        }

    }
}
drkunibar
  • 1,327
  • 1
  • 7
  • 7
  • Thanks for your solution. can you point out why was my program not doing this thing. – arindrajit Apr 05 '14 at 14:52
  • @arindrajit Yes I'm here. Sorry, but I did not wait all day long of problems from stackoverflow. Your misstake is insinde your client program. There is a loop `while ((b = bfINPUT.read()) != -1) {`. This loop waits untill the server close the input stream (but this should never happens). Your client never leave this loop. That's the reason we need different threads for reading an writing, because both could happen at the same time. Hope that helps. – drkunibar Apr 05 '14 at 15:12