Click here to Skip to main content
15,916,442 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello. I am beginner in network programming. I am gonna write code for client and ask user for some question in client and user will also input the choice based on integer. Supposedly, the server should return the user's input to the client. But it not works. I hope you guys can help me and give example. Thank you in advance.

What I have tried:

Server code

Java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TestServer
{
    private static ServerSocket servSock;
    private static final int PORT = 1234;

    public static void main(String[] args)
    {
        System.out.println("Opening port...\n");
        try
        {
            servSock = new ServerSocket(PORT);      //Step 1.
        }
        catch(IOException ioEx)
        {
            System.out.println("Unable to attach to port!");
            System.exit(1);
        }
        do
        {
            handleClient();
        }
        while (true);
    }

    private static void handleClient()
    {
        Socket link = null;                     			//Step 2.
        try
        {
            link = servSock.accept();        				//Step 2.

            Scanner input = new Scanner(link.getInputStream()); 	//Step 3.
            PrintWriter output = new PrintWriter(link.getOutputStream(),true); 	//Step 3.

            int numMessages = 50;
            String message = input.nextLine();      			//Step 4.
            while (!message.equals("***CLOSE***"))
            {
                System.out.println("Message received.");
                numMessages++;
                output.println("Message " + numMessages + ": " + message);   		//Step 4.
                message = input.nextLine();
            }
            output.println(numMessages + " messages received."); 	//Step 4.
        }
        catch(IOException ioEx)
        {
            ioEx.printStackTrace();
        }
        finally
        {
            try
            {
                System.out.println( "\n* Closing connection... *");
                link.close();                    //Step 5.
            }
            catch(IOException ioEx)
            {
                System.out.println("Unable to disconnect!");
                System.exit(1);
            }
        }
    }
}

Client code

Java
package testclient;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class TestClient
{

    private static InetAddress host;
    private static final int PORT = 1234;
    
    public static void main(String[] args)
    {
       try
       {
           host = InetAddress.getLocalHost();
       }
       catch(UnknownHostException uhEx)
       {
           System.out.println("Host ID not found");
           System.exit(1);
       }
       accessServer();
    }
    
    private static void accessServer()
    {
        Socket link = null;
        
        try
        {
            link = new Socket(host,PORT);
            Scanner input = new Scanner(link.getInputStream());
            
            PrintWriter output = new PrintWriter(link.getOutputStream(),true);
            
            Scanner userEntry = new Scanner(System.in);
            
            String message, response;
            do
            {
                System.out.println("Are you in healthy condition?");
                message = userEntry.nextLine();
                System.out.println("Are you in happy mode?");
                message = userEntry.nextLine();
                System.out.println("Are you in sad condition?");
                message = userEntry.nextLine();
                System.out.println("Are you in sick condition?");
                message = userEntry.nextLine();
                response = input.nextLine();
                System.out.println("\nServer " +response);
                output.println(message);
                response = input.nextLine();
                System.out.println("\nServer " +response);
            }while(!message.equals("***CLOSE***"));
        }
        catch(IOException ioEx)
        {
            ioEx.printStackTrace();
        }
        
        finally
        {
            try
            {
                System.out.println("\n*Closing connection...*");
                link.close();
            }
            catch(IOException ioEx)
            {
                System.out.println("Unable to disconnect...");
                System.exit(1);
            }
        }
    }     
}
Posted
Updated 8-Jan-18 3:13am
v2
Comments
ZurdoDev 8-Jan-18 8:00am    
Why does it not work?
eddyfy 8-Jan-18 8:23am    
After, i have added another question, it doesn't work for me. it cannot attach to the port
eddyfy 8-Jan-18 8:24am    
After, i had added another question it doesn't work in the server.
ZurdoDev 8-Jan-18 8:42am    
You answered what is not working. You need to answer why. And since we can't run your code, you need to do some debugging and find out what is happening and why. Then you can fix it.

You can't just call up a mechanic and tell them that you can't drive to work. You have to figure out why.
eddyfy 8-Jan-18 9:46am    
I am sorry. But the server cannot attach to the port. So, that it can't return back the user input's to the client

1 solution

The sequence on the client for each question should be:

  • Print on screen
  • Read user input
  • Send to server
  • Receive response from server
  • Print response on screen
But your code does not do that. It first prints questions and reads the user input for four questions and then waits for a server response but without sending to the server.

It should be like
Java
System.out.println("Are you in healthy condition?");
message = userEntry.nextLine();
output.println(message);
response = input.nextLine();
System.out.println("\nServer " +response);

// Next question goes here repeating the above
 
Share this answer
 
Comments
eddyfy 8-Jan-18 9:40am    
But the server still doesn't work. It said that unable to attach to the port
Jochen Arndt 8-Jan-18 9:52am    
That is probably because you are not closing the socket and the port is therefore blocked from the previous execution.

How do you have stopped your server application?
You have an infinite while loop in main and System.Exit is only called when there is an exception when closing the link socket. Even when System.Exit is called, it is recommended to close the socket before.

Try to add
servSock.close();
after closing the link socket or do that in your main() function and remove the infinite loop (you already have a loop in your handling function).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900