Jump to content

Client to Server Messaging- Java

canadianultra

Hey guys, I would like some input on my relatively simple Client to server messaging program

 

I think the Client part is OK, but the server bit is a bit broken

 

The program actually sort of works (client can send messages to server) 

 

I am having trouble putting a username + password on it (set it up for a default password + username , not storing multiple usernames + password) (currently using username:1, password:2)

 

And I would like for the server the receive the clients Ip, when it connects, if anyone has any spare time and some java experience it would be greatly appreciated

 

Client: 

import java.lang.*;import java.io.*;import java.net.*;import java.util.Scanner;class LongClient {   public static void main(String args[]) {	       try {         Socket skt = new Socket("localhost", 1234);         BufferedReader in = new BufferedReader(new            InputStreamReader(skt.getInputStream()));  Scanner kbReader = new Scanner(System.in);  PrintWriter out = new PrintWriter(skt.getOutputStream(), true);   out.flush();        String message, servermessage;        InetAddress clientip = InetAddress.getLocalHost();  System.out.println("Preparing to chat...");  out.println("Client IP Address: " + clientip); // sends message to client giving ip  out.println("Client hostname: " + clientip.getHostAddress()); // send message to client giving computer name   do{   if (in.ready()){    servermessage=in.readLine();    System.out.println("server>: "+servermessage);   }      message=kbReader.nextLine();   out.println(message);   out.println("Done");   //message="bye";   //out.println("bye");   Thread.currentThread().sleep(300);  }while (!message.equals("bye"));         out.close();in.close();      }      catch(Exception e) {         System.out.print(e);      }   }	}

Server:

import java.lang.*;import java.io.*;import java.net.*;class LongServer {	public static void main(String args[]) throws IOException {		String data = "Welcome to My Server"; //welcome message		String data1 = "enter username"; //welcome message		String message; 		int idstats1 = 0; //verifyed username		int idstats2 = 0; //verifyed password 		int verify1 = 0;		try {			//Detecting the localhost's ip address			InetAddress localaddr = InetAddress.getLocalHost();			System.out.println ("Local IP Address : " + localaddr );			System.out.println ("Local hostname : " + localaddr.getHostAddress());			// Creating a server socket for connection			ServerSocket srvr = new ServerSocket(1234);			System.out.println("Waiting for connection on "+localaddr);			// Accept incoming connection			Socket skt = srvr.accept();			System.out.print("Server has connected!\n");			// get Input and Output streams			PrintWriter out = new PrintWriter(skt.getOutputStream(), true);			out.flush();			BufferedReader in = new BufferedReader(new					InputStreamReader(skt.getInputStream()));			System.out.print("Sending string: '" + data + "'\n");			out.println(data  ); //sends welcome message			System.out.print("Sending string: '" + data1 + "'\n");			out.println(data1); //sends welcome message						message=in.readLine(); //reads the line typed in			while(verify1==0){								if (idstats1 == 0) {			//if the client is not verifyed, it asks for a password					out.println("enter username");				}			if (idstats2 == 0) {			//if the client is not verifyed, it asks for a password					out.println("enter password");				}										if (message.equals("1")){ //is the input is password, then the client is verifyed						out.println("Username accepted");						idstats1=1;					}					if (message.equals("2")){ //is the input is password, then the client is verifyed						out.println("Password Accepted");						idstats2=1;					}					if (idstats1==1 && idstats2==1){						verify1=1;					}								}					if (verify1==1) { //if client is verifyed, it asks them to type a message and prints it to the console				out.println("enter a message");				System.out.println("client>"+message);			}			if (message.equals("bye")){ //if the client enters "bye" then the server closes				out.println("Server closing");				System.out.println("server>Server closing");			}				while(!message.equals("bye")); {				out.close();				skt.close();				srvr.close();}		}catch(BindException e){				e.printStackTrace();				System.out.print("A server is already running on the same port.");    	  			}catch(SocketException e) {				e.printStackTrace();				System.out.print("Client has disconnected rudely.");			}catch(Exception e){				e.printStackTrace();				System.out.print(e);			}		}	}

Thanks for your help!!

CPU: i5 4670k GPU: GTX 770 Mobo: Z87-UD3H RAM: 8Gb Ripjaws Case: Corsair 200R PSU: Corsair RM750

Link to comment
Share on other sites

Link to post
Share on other sites

so what happens now? when does the program stop working as expected?

 

i think that you're missing some sort of sync between the client and the server anyway: i never saw sockets used in java, and i have to say that those Socket and ServerSocket classes look quite convenient, but it looks like you're "abusing" of their transparency, you throw a bunch of messages at the client without waiting for a response to the previous one

 

and this is an infinite loop, it enters and it keeps evaluating the same message because the in.readLine() is out of the loop

			message=in.readLine(); //reads the line typed in			while(verify1==0){								if (idstats1 == 0) {			//if the client is not verifyed, it asks for a password					out.println("enter username");				}			if (idstats2 == 0) {			//if the client is not verifyed, it asks for a password					out.println("enter password");				}										if (message.equals("1")){ //is the input is password, then the client is verifyed						out.println("Username accepted");						idstats1=1;					}					if (message.equals("2")){ //is the input is password, then the client is verifyed						out.println("Password Accepted");						idstats2=1;					}					if (idstats1==1 && idstats2==1){						verify1=1;					}								}
Link to comment
Share on other sites

Link to post
Share on other sites

 

so what happens now? when does the program stop working as expected?

 

i think that you're missing some sort of sync between the client and the server anyway: i never saw sockets used in java, and i have to say that those Socket and ServerSocket classes look quite convenient, but it looks like you're "abusing" of their transparency, you throw a bunch of messages at the client without waiting for a response to the previous one

 

and this is an infinite loop, it enters and it keeps evaluating the same message because the in.readLine() is out of the loop

			message=in.readLine(); //reads the line typed in			while(verify1==0){								if (idstats1 == 0) {			//if the client is not verifyed, it asks for a password					out.println("enter username");				}			if (idstats2 == 0) {			//if the client is not verifyed, it asks for a password					out.println("enter password");				}										if (message.equals("1")){ //is the input is password, then the client is verifyed						out.println("Username accepted");						idstats1=1;					}					if (message.equals("2")){ //is the input is password, then the client is verifyed						out.println("Password Accepted");						idstats2=1;					}					if (idstats1==1 && idstats2==1){						verify1=1;					}								}

the program gets hung up on the verification phase, it just keeps asking for a username and password and does not stop, I think your right about the loop, I just don't exactly know how to solve it

CPU: i5 4670k GPU: GTX 770 Mobo: Z87-UD3H RAM: 8Gb Ripjaws Case: Corsair 200R PSU: Corsair RM750

Link to comment
Share on other sites

Link to post
Share on other sites

the program gets hung up on the verification phase, it just keeps asking for a username and password and does not stop, I think your right about the loop, I just don't exactly know how to solve it

start by taking the readline() inside the loop
Link to comment
Share on other sites

Link to post
Share on other sites

import java.lang.*;import java.io.*;import java.net.*;class LongServer {    public static void main(String args[]) throws IOException {        String data = "Welcome to My Server"; //welcome message        String data1 = "enter username"; //welcome message        String message;         int idstats1 = 0; //verifyed username        int idstats2 = 0; //verifyed password         int verify1 = 0;        try {            //Detecting the localhost's ip address            InetAddress localaddr = InetAddress.getLocalHost();            System.out.println ("Local IP Address : " + localaddr );            System.out.println ("Local hostname : " + localaddr.getHostAddress());             //Creating a server socket for connection            ServerSocket srvr = new ServerSocket(1234);            System.out.println("Waiting for connection on "+localaddr);             //Accept incoming connection            Socket skt = srvr.accept();            System.out.print("Server has connected!\n");             //get Input and Output streams            PrintWriter out = new PrintWriter(skt.getOutputStream(), true);            out.flush();            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));            System.out.print("Sending string: '" + data + "'\n");            out.println(data); //sends welcome message            System.out.print("Sending string: '" + data1 + "'\n");            out.println(data1); //sends welcome message                      while(verify1 == 0) {             	  message = in.readLine(); //reads the line typed in                if (idstats1 == 0) {                    //if the client is not verifyed, it asks for a password                    out.println("enter username");                }                if (idstats2 == 0) {                    //if the client is not verifyed, it asks for a password                    out.println("enter password");                }                if (message.equals("1")) {                     //is the input is password, then the client is verifyed                    out.println("Username accepted");                    idstats1 = 1;                     }                if (message.equals("2")) {                     //is the input is password, then the client is verifyed                    out.println("Password Accepted");                    idstats2 = 1;                     }                if (idstats1 == 1 && idstats2 == 1) {                    verify1 = 1;                }                                       }             message = in.readLine(); //reads the line typed in           while (verify1 == 1) {        	   message = in.readLine(); //reads the line typed in                //if client is verifyed, it asks them to type a message and prints it to the console                out.println("enter a message");                System.out.println("client>"+message);            }            if (message.equals("bye")) {                 //if the client enters "bye" then the server closes                out.println("Server closing");                System.out.println("server>Server closing");            }            while(!message.equals("bye")); {                out.close();                skt.close();                srvr.close();            }        } catch(BindException e) {            e.printStackTrace();            System.out.print("A server is already running on the same port.");                } catch(SocketException e) {            e.printStackTrace();            System.out.print("Client has disconnected rudely.");        } catch(Exception e) {            e.printStackTrace();            System.out.print(e);            }    }}

I made a couple changes with the next line stuff, now after a couple times(idk when it dosent always go though) it gets verofied and messages start going through, however it does not send the reponse to the server "enter a message" or mention that the user in now verified

CPU: i5 4670k GPU: GTX 770 Mobo: Z87-UD3H RAM: 8Gb Ripjaws Case: Corsair 200R PSU: Corsair RM750

Link to comment
Share on other sites

Link to post
Share on other sites

you should print the received message to see what the server reads. the first reads should go wasted because it's receiving those messages

  out.println("Client IP Address: " + clientip); // sends message to client giving ip  out.println("Client hostname: " + clientip.getHostAddress()); // send message to client giving computer name

on a sidenote, the server should be able to get those informations by itself

 

and this is not your problem now, but beware you have another infinite loop going on

           while (verify1 == 1) {        	   message = in.readLine(); //reads the line typed in                //if client is verifyed, it asks them to type a message and prints it to the console                out.println("enter a message");                System.out.println("client>"+message);            }

as i said, it just seems to not be a well established protocol, in every moment both the client and server should know what kind of thata they have to wait for or they have to send, but as of now they don't, it's a bit confused, client and server are both shouthing in each other's face

Link to comment
Share on other sites

Link to post
Share on other sites

You can thank me later ;)

https://www.dropbox.com/sh/76l94h3ice3xil4/WKWw2q3zPY
 
EDIT: The TCP (client and server) connection is what you are looking for.

I believe you are having trouble linking the write statements for client and server.
Each outToserver on a client should have its own inFromClient variable on the server. (naming conventions saves time and prevents bugs)
 
 
"And I would like for the server the receive the clients Ip, when it connects,"
 
Client

 DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());InetAddress IPAddress = InetAddress.getLocalHost(); System.out.println(IPAddress); outToServer.writeBytes(IPAddress);

 
Server:

BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); InetAddress clientIP = inFromClient.readLine();   System.out.println(clientIP);

I haven't tested the lines above but convert the IP to strings is necessary

------------------------------------

     ~ Live Love Code ~

------------------------------------

Link to comment
Share on other sites

Link to post
Share on other sites

-snip-

well he already has that, both the client and server applications have an in BufferedReader variable and an out PrintWriter variable, so he got away nicely with that

he just have to establish a well defined protocol/sync so that the communication is not left in chaos

 

edit:

the server can use the getInetAddress() method to get the client's IP without needing the client to send it as a message

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×