dumbnerd111
dumbnerd111

Reputation: 21

Java Message sent from client to server

I'm using a socket to connect my client with the server, I need a way so that when somebody tries to login on the client with an account, it sends the username and password to the server, and checks if the account exists. I just need to know how to make it send the message to the server when they press login.

i tried this to make it send a message to the server

public static void sendmsg(String a, String b)
    {
        try
        {
            String host = "127.0.0.1";
            int port = 43655;
            InetAddress address = InetAddress.getByName(host);
            socket = new Socket(address, port);

            //Send the message to the server
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);


            String sendMessage = a;
            bw.write(sendMessage);
            bw.flush();
            System.out.println("Message sent to the server : "+sendMessage);

            //Get the return message from the server
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String message = br.readLine();
            System.out.println("Message received from the server : " +message);
        }
        catch (Exception exception) 
        {
            exception.printStackTrace();
        }
        finally
        {
            //Closing the socket
            try
            {
                socket.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }

Upvotes: 2

Views: 233

Answers (2)

Marcelo Tataje
Marcelo Tataje

Reputation: 3881

nice you are working with Sockets, well I have an approach you can try, and maybe if it is useful you can consider for your implementation.

First of all I will create an entity to handle those values and fill it with the incoming data.

class UserAuth {
    private String username;
    private String password;
    //Consider here your getters and setters, I am not including them       
}

I will use the entity as the parameter for the method while sending and maybe you can fill it as something like:

UserAuth attemptingUser = new UserAuth(...)

ObjectInputStream works fine for these kind of scenarios. If you still want to work with Strings, you can use BufferedReader and try to merge your username and password as one single String and use the .readLine() method to obtain (separated with commas), then use String methods such Split but I find that could take some more time, should be better if you handle it with an object. But it depends on the complexity you want to add to your application :).

class AuthClient {

    public void sendMsg(UserAuth attemptingUser) {
        String host =  "localhost";
        int port = 2055;
        //1. Create the socket
        Socket sender = new Socket(host, port);
        //2. Create an object output stream to write the object into the stream
        ObjectOutputStream outputWriter = new ObjectOutputStream(sender.getOutputStream());
        //3. Write (send the object)
        outputWriter.writeObject(attemptingUser);
        //4. Close
        outputWriter.close();
        sender.close();
    }
}

class AuthServer {

    ServerSocket ss = new ServerSocket(2055);

    public void receiveMsg() {
        //1. Accept the connection
        Socket conn = ss.accept();
        //2. Receive the flow
        ObjectInputStream readStream = new ObjectInputStream(conn.getInputStream());
        //3. Read the object
        UserAuth userReceived = readStream.readObject();
        //4. Verify against file, db or whatever
        if (userReceived.getUsername().equals("admin") && userReceived.getPassword().equals("admin")) {
            //Authentication
        }
    }

}

(This is added as the part I edit for what you asked me in the comments)

public void sendMsg(String username, String password) {
            String host =  "localhost";
            int port = 2055;
            //1. Create the socket
            Socket sender = new Socket(host, port);
            //2. Create the UserAuth object based on the parameters you received
            UserAuth myuser = new UserAuth();
            myuser.setUsername(username);
            myuser.setPassword(password);
            //3. Follow same instructions for the creation of ObjectOutputStream...
            ObjectOutputStream objectWriter = new ObjectOutputStream(sender.getOutputStream());
            objectWriter.writeObject(myuser);
            //That is what I would use if I keep your structure
        }

If you want to keep your structure using Strings, I would simplify and reduce impact of I/O by using the String methods. Since you know you are always expecting user/password, I would merge your two params in one single String or use special char and on server side handle with StringTokenizer class. Or maybe handle with the "split" method. You have many options here.

So far, this will be my approach for the problem you are facing. Hope it helps somehow. Best regards and happy coding :).

Upvotes: 1

Brad
Brad

Reputation: 15909

What you have done looks OK to me but it all depends on what the server is expecting to receive. What is the terminating character as you have not sent one unless it's already contained within your String a variable.

If the server is expecting an end of line character (which you don't currently send) you can use a PrintWriter instead of a BufferedWriter like this

pw = new PrintWriter(socket.getOutputStream(), true);
pw.println(a);

Your server would then be doing something like this

BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String value = br.readLine();

Upvotes: 0

Related Questions