2015-07-07 3 views
0

Проблема в том, что мне нужно показать историю чата на стороне клиента без передачи файла чата. Сервер и клиент находятся на том же компьютере, что и мой компьютер. Сервер считывает char с помощью char из файла и записывает его в сокет. Клиент должен прочитать его как строку, чтобы получить точную историю чата, как сохраненную в файле. Но по моему методу печать одного символа в одной строке
import java.io. *;Чат-сервер: Распечатать историю чатов java

class Server 
    { 
     public static void main(String dt[]) 
     { 
      ServerSocket sskt=null;Socket skt=null; 
      InputStreamReader isrin=null,isrout=null; 
      BufferedReader brin=null,brout=null;PrintWriter pw=null; 
      FileWriter fw=null;FileReader fr=null; 
      DataInputStream dis=null;DataOutputStream dos=null; 
      try 
      { 
       sskt=new ServerSocket(1234); 
       System.out.println("Waiting for Client"); 
       skt=sskt.accept(); 
       System.out.println("Connected to client"); 

       isrin=new InputStreamReader(skt.getInputStream()); 
       brin=new BufferedReader(isrin); 

       isrout=new InputStreamReader(System.in); 
       brout=new BufferedReader(isrout); 
       pw=new PrintWriter(skt.getOutputStream(),true); 
       dis=new DataInputStream(skt.getInputStream()); 
       dos=new DataOutputStream(skt.getOutputStream()); 

       SimpleDateFormat sdf=new SimpleDateFormat("dd_MM_yy"); 
       Date date=new Date(); 
       String ing=sdf.format(date); 
       fw=new FileWriter(ing+".txt",true); 

       //do{ 
       String str; 
       str=brin.readLine(); 
       int c=Integer.parseInt(str); 
       switch(c) 
       { 
        case 1: 
        { 
         System.out.println("New Chat Stared"); 
         String msg=""; 
         do 
         { 
         SimpleDateFormat sdf1=new SimpleDateFormat("hh:mm:ss"); 
         Date d=new Date(); 
         String in=sdf1.format(d); 

         msg=brin.readLine(); 
         System.out.println("Client says " + msg); 
         fw.write("Client "+in+" "+msg); 

         msg=brout.readLine(); 
         pw.println(msg); 
         fw.write("Server "+in+" "+msg); 
         } 
         while(!msg.equals("bye")); 
         fw.close(); 
        break; 
        } 
        case 2: 
        { 
         String d=brin.readLine(); 
         File file=new File(d+".txt"); 
         if(file.exists()) 
         { 
          dos.writeBoolean(true); 
          System.out.println("Displaying Contents of File"); 
          fr=new FileReader(d+".txt"); 
          int z; 
          while((z=fr.read())!=-1) 
          { 
           pw.println((char)z); 
          } 
          fr.close(); 
          dos.writeBoolean(true); 
//it writes the contents of the file on the socket one char by char 
          } 
          else 
          { 
           dos.writeBoolean(false); 
          } 
          break; 
         } 
         case 3: 
         { 
          System.out.println("Client Exited"); 
          System.exit(0); 
          break; 
         } 
         default: 
         { 
          System.out.println("Invalid choice"); 
          break; 
         } 
        } 
       //}while(true); 

      } 
      catch(Exception e) 
      { 
       System.out.println(e); 
      } 
      finally 
      { 
       try 
       { 
        pw.close(); 
        brin.close(); 
        isrin.close(); 
        skt.close(); 
        sskt.close(); 
       } 
       catch(Exception ex) 
       { 
        System.out.println(ex); 
       } 
      } 
     } 
    } 

    class Client 
    { 
     public static void main(String dt[]) 
     { 
      Socket skt=null; 
      InputStreamReader isrout=null,isrin=null; 
      BufferedReader brout=null,brin=null; 
      PrintWriter pw=null; 
      DataOutputStream dos=null; 
      DataInputStream dis=null; 
      FileReader fw=null; 
     try 
     { 
       skt=new Socket("127.0.0.1",1234); 
       System.out.println("Connected to Server"); 

       isrout=new InputStreamReader(System.in); 
       brout=new BufferedReader(isrout); 
       pw=new PrintWriter(skt.getOutputStream(),true); 
       isrin=new InputStreamReader(skt.getInputStream()); 
       brin=new BufferedReader(isrin); 
       dos=new DataOutputStream(skt.getOutputStream()); 
       dis=new DataInputStream(skt.getInputStream()); 

      //do 
      //{ 
       System.out.println("1. To start a chat"); 
       System.out.println("2. To view chat history"); 
       System.out.println("3. Exit"); 
       String str=""; 
       str=brout.readLine(); 
       pw.println(str); 
       int a=Integer.parseInt(str); 
       switch(a) 
       { 
        case 1: 
        { 
         String msg=""; 
         do 
         { 
         msg=brout.readLine(); 
         pw.println(msg); 
         msg=brin.readLine(); 
         System.out.println("Server Says " + msg); 
         } 
         while(!msg.equals("bye")); 
         break; 
        } 
        case 2: 
        { 
         System.out.println("Enter date of chat history"); 
         String date=brout.readLine(); 
         pw.println(date); 
         if(dis.readBoolean()) 
         { 
          System.out.println("Chat Exists"); 
          fw=new FileReader("H:\\Java Programs\\chatser\\chat\\client\\"+date+".txt"); 
          int ab; 
          while((ab=fw.read())!=-1) 
          { 
           System.out.println(brin.readLine()); 
          } 
          fw.close(); 
         } //this syntax will read from the socket char by char and print one char after another in next line. i need to get chat history as string without copying the file at client side 
         else 
         { 
          System.out.println("Incorrect Entity"); 
         } 
         break; 
        } 
        case 3: 
        { 
         System.out.println("Thank you"); 
         System.exit(0); 
         break; 
        } 
        default: 
        { 
         System.out.println("Incorrect Entity"); 
        } 
       } 
      //}while(true); 

     } 
      catch(Exception e) 
      { 
       System.out.println(e); 
      } 
      finally 
      { 
       try 
       { 
        pw.close(); 
        brout.close(); 
        isrout.close(); 
        skt.close(); 
       } 
       catch(Exception ex) 
       { 
        System.out.println(ex); 
       } 
      } 
     } 
} 
+0

клиент и сервер находятся в отдельных файлах Java –

ответ

1

Посмотрите на следующий фрагмент кода:

int z; 
while((z=fr.read())!=-1) { 
    pw.println((char)z); 
} 

Вы конвертируете число чтения в полукокса, который будет только держать один символ. Это не приведет к печати всего значения, которое вы ищете. Если вы хотите преобразовать это целое число в печатную строку, попробуйте что-то вроде этого:

pw.println(Integer.toString(z)) 
Смежные вопросы