5

CLIENT -SERVER SOCKET PROGRAMMING

 2 years ago
source link: https://www.codesd.com/item/client-server-socket-programming.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

CLIENT -SERVER SOCKET PROGRAMMING

advertisements

I have written client-server message sending program using sockets in Java, which is working fine, but if the string length of the previous message is greater than the present in.read(b5), string message is printed with previous message characters added to it. This problem is due to previous stored characters in byte array.

How to clear the byte array for every loop? How can I resolve this?

CLIENT code:

try
  {
    String add=args[0];
    int port=Integer.parseInt(args[1]);
    Socket s=new Socket(add,port);
    OutputStream out=s.getOutputStream();
    InputStream in=s.getInputStream();
    BufferedReader bufIn = new BufferedReader( new InputStreamReader( in ) );
    BufferedWriter bufOut = new BufferedWriter( new OutputStreamWriter( out ) );
    byte b1[]=new byte[100];
    byte b2[]=new byte[100];
    while(true)//infinite loop
    {
      System.out.println("To Server:");
      System.in.read(b1);  //reading from keyboard
      out.write(b1);       //writing to server
      in.read(b2);         //reading from server
      String s1=new String(b2);
      String s2=s1.trim();
      System.out.println("From Server:"+s2);
    }
  }
  catch (Exception e)
  {
    System.err.println(e);
  }

SERVER code:

try
{
  int port=Integer.parseInt(args[0]);
  ServerSocket ss=new ServerSocket(port);
  while(true)   //this loop for diff. no. of clients
  {
    Socket s=ss.accept();
    InputStream in=s.getInputStream();
    OutputStream out=s.getOutputStream();
    byte b1[]=new byte[100];
    byte b2[]=new byte[100];
    while(true)   //this loop for one client diff. no. of times.
    {
      in.read(b1);
      String s1=new String(b1);
      String s2=s1.trim();
      System.out.println("From Client:"+s2);
      System.out.print("To Client:");
      System.in.read(b2);
      out.write(b2);
    }
  }
}
catch (Exception e)
{
  System.err.println(e);
}


add out.flush(); to the bottom of your loop. Read the javadoc for more info. See relevant part below:

"Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination. "


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK