简体   繁体   中英

While loop in client-server program

so i was i have to do some simple client-server program. Server side `

public static void main(String[] args) throws IOException
{
    ServerSocket ss = null;
    try{ss= new ServerSocket(119);}
    catch(IOException ioe){System.out.println("Can't connect to port.");}

    Socket sock = null;
    try{sock = ss.accept();}
    catch(IOException ioe){System.out.println("Can't connect to client.");}
    System.out.println("Connection successful.");

    PrintStream out = null;
    Scanner in = null;

    try{
        out = new PrintStream(sock.getOutputStream());
        in = new Scanner(sock.getInputStream());
    }catch(Exception e)
    {
        System.out.println("Error.");
    }

    String line;
    String lines = "";

    while((line = in.nextLine()) != null)
    {
        switch(line)
        {
        case "list":out.println("Printing something");break;
        case "loop":
        {
            FileReader fr = new FileReader("D:\\Eclipse\\TestFiles\\text2.txt");
            BufferedReader br = new BufferedReader(fr);
            while((lines = br.readLine()) != null)
            {
                out.println(lines);
            }
            break;
        }
        default:
        {
            if(!(line.equals("end"))) out.println("Unknown command.Try again.");break;
        }
        }
        out.flush();
        if(line.equals("end"))
        {
            out.println("Connection over.");
            break;
        }
    }

    try{
        in.close();
        out.close();
        sock.close();
        ss.close();
    }catch(IOException ioe){}

}

`

Client side

public static void main(String[] args)
{
    Socket sock = null;
    PrintStream out = null;
    Scanner in = null;
    Scanner sIn = null;

    try{
        sock = new Socket("localhost",119);
        out = new PrintStream(sock.getOutputStream());
        in = new Scanner(sock.getInputStream());
        sIn = new Scanner(System.in);
    }catch(Exception e){
        System.out.println("Error connecting to server.");
        System.exit(1);
    }

    System.out.println("Connection successful.");

    String temp = "";

    while((temp = sIn.nextLine()) != null)
    {
        out.println(temp);
        while(in.hasNextLine())System.out.println(in.nextLine());
        out.flush();
        if(temp.equals("end")) break;
    }

    try{
        sock.close();
        in.close();
        out.close();
    }catch(IOException ioe){}

}

My problem is that on the client side when the second while loop(the on inside the first while loop) has to end, it does not and i am just entering commands in the client without any response

Fixes

  1. Use PrintWriter for to write to the socket and BufferedReader to read from the socket. Open the PrintWriter in auto flush mode true in the below statement signifies that. This way you don't have to worry about flushing the stream.

     PrintWriter out = new PrintWriter(sock.getOutputStream(),true); 
  2. Your closing statements are within loop, which closes streams and you cannot use them for the next iteration because you will get an exception . Pull them out of the while loop.
  3. Unnecessary braces to delimit cases in the switch.
  4. Your connection termination statements should be out of the switch case. Only then break will have a effect on the loop instead on the switch.
  5. I used br.ready() to sense if the stream is ready to be read and then iterating through the loop. This is effective than your version.

     while((temp = sIn.nextLine()) != null) { out.println(temp); Thread.currentThread().sleep(1000); while(in.ready())System.out.println(in.readLine()); out.flush(); if(temp.equals("end")) break; } 
  6. Thread.currentThread().sleep(1000), is to get handle of the main thread and sleep it for 1000ms, this way I am letting br be ready with the server response. otherwise br.ready() will be false, for the present request, and it gets ready in the next iteration. I think you know what I trying to convey.

I did not check the case loop;

Server

import java.net.*;
import java.io.*;
import java.util.*;

public class chatServer
{   
public static void main(String[] args) throws IOException
{
    ServerSocket ss = null;
    try
    {
        ss= new ServerSocket(8000);
    }
    catch(IOException ioe){System.out.println("Can't connect to port.");}

    Socket sock = null;
    try{sock = ss.accept();}
    catch(IOException ioe){System.out.println("Can't connect to client.");}
    System.out.println("Connection successful.");

    PrintWriter out = null;
    Scanner in = null;

    try{
        out = new PrintWriter(sock.getOutputStream(),true);
        in = new Scanner(sock.getInputStream());
    }catch(Exception e)
    {
        System.out.println("Error.");
    }

    String line;
    String lines = "";

    while((line = in.nextLine()) != null)
    {
        switch(line)
        {
            case "list":
                out.println("1. bla  |  2. ble  |  3. bli");break;
            case "group":out.println("Here group will be chosen.");break;
            case "header":out.println("Returns header.");break;
            case "loop":
                FileReader fr = new FileReader("D:\\Eclipse\\TestFiles\\text2.txt");
                BufferedReader br = new BufferedReader(fr);
                while((lines = br.readLine()) != null)
                {
                    out.println(lines);
                }
                break;
            default:
                if(!(line.equals("end")))
                {
                    out.println("Unknown command.Try again.");
                    break;
                }
        }
        if(line.equals("end"))
        {
            out.println("Connection over.");
            break;
        }
    }
    try{
            in.close();
            out.close();
            sock.close();
            ss.close();
        }catch(IOException ioe){}

}

}

Client

import java.net.*;
import java.io.*;
import java.util.*;

public class chatClient
{
public static void main(String[] args) throws IOException, InterruptedException
{
    Socket sock = null;
    PrintStream out = null;
    BufferedReader in = null;
    Scanner sIn = null;

    try
    {
        sock = new Socket("localhost",8000);
        out = new PrintStream(sock.getOutputStream());
        in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        sIn = new Scanner(System.in);
    }
    catch(Exception e)
    {
        System.out.println("Error connecting to server.");
        System.exit(1);
    }

    System.out.println("Connection successful.");

    String temp = "";

    while((temp = sIn.nextLine()) != null)
    {
        out.println(temp);
        Thread.currentThread().sleep(1000);
        while(in.ready())System.out.println(in.readLine());
        out.flush();
        if(temp.equals("end")) break;
    }

    try
    {
        sock.close();
        in.close();
        out.close();
    }
    catch(IOException ioe){}

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM