Results 1 to 19 of 19
Like Tree2Likes
  • 1 Post By gimbal2
  • 1 Post By gimbal2

Thread: not able to send byte array from server to client

  1. #1
    maddy14 is offline Member
    Join Date
    May 2013
    Posts
    25
    Blog Entries
    1
    Rep Power
    0

    Default not able to send byte array from server to client

    I have a task to do this.
    Create a client and server socket interaction which accepts byte data and converts the byte data data received at server in the String and send back the response with the confirmation of the data conversation with success/unsuccess as the data passed will be with fix data length format so the validation should be done at server end.

    As for e.g.

    there are fields which ur sending to server like,

    field 1 - number
    field 2 - String
    field 3 as Floating number i.e. 108.50

    After conversion from byte to String :
    152|any msg|108.50

    In Byte it will be something like this,

    10101|1001010010000000011000000000|1110111011

    I have tried the following programs to do this

    Server.java
    Java Code:
        public class Server extends Thread
        {
        	private ServerSocket serverSocket;
        
        	public Server(int port) throws IOException
        	{
        		serverSocket = new ServerSocket(port);
        		//serverSocket.setSoTimeout(100000);
        	}
        
        	public void run()
        	{
        		while(true)
        		{
        			try
        			{
        				Socket server = serverSocket.accept();
        				byte Message[]=null;
        				DataInputStream in =
        						new DataInputStream(server.getInputStream());
        
        				ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        
        				int nRead;
        				byte[] data = new byte[16384];
        				while ((nRead = in.read(data, 0, data.length)) != -1) {
        					buffer.write(data, 0, nRead);
        				}
                                        System.out.println("On this line"); //This doesnt get printed
        				buffer.flush();
        
        				data= buffer.toByteArray();
        				
        				System.out.println(data);
        				String convertmsg = new String(data);
        				System.out.println("Msg converted "+convertmsg);
        				DataOutputStream out =
        						new DataOutputStream(server.getOutputStream());
        				System.out.println("below dataoutputstream");
        				out.write("Success".getBytes());
        				server.close();
        			}catch(SocketTimeoutException s)
        			{
        				System.out.println("Socket timed out!");
        				break;
        			}catch(IOException e)
        			{
        				e.printStackTrace();
        				break;
        			}
        		}
        	}
        	public static void main(String [] args)
        	{
        		int port = 4003;
        		try
        		{
        			Thread t = new Server(port);
        			t.start();
        		}catch(IOException e)
        		{
        			e.printStackTrace();
        		}
        	}
        }
    client

    Java Code:
       public class Client {
        	public static void main(String args[]) throws IOException
        	{
        		int userinput =1;
        		while(userinput==1)
        		{
        			String serverName = "192.168.0.8";
        			int port = 4003;
        			try
        			{
        				System.out.println("Connecting to " + serverName
        						+ " on port " + port);
        				Socket client = new Socket(serverName, port);
        				System.out.println("Just connected to "
        						+ client.getRemoteSocketAddress());
        				OutputStream outToServer = client.getOutputStream();
        				DataOutputStream out =
        						new DataOutputStream(outToServer);
        				System.out.println("above out.wirte()");
        				out.write("any msg".getBytes());
        
        
        				InputStream inFromServer = client.getInputStream();
        				DataInputStream in =
        						new DataInputStream(inFromServer);
        				ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        
        				int nRead;
        				
        				System.out.println("converting array "+in);
        				byte[] data = IOUtils.toByteArray(in);
        
        				
        				System.out.println(data);//This line doesnt get printed
        				//System.out.println("Server says " + in.readUTF());
        				client.close();
        			}catch(IOException e)
        			{ 
        				e.printStackTrace();
        			}
        			System.out.println("Enter userinput ");
        			DataInputStream dis = new DataInputStream(System.in);
        			String s = dis.readLine();
        			userinput = Integer.parseInt(s);
        		}
        	}
        
        }

    If i send data from client to server in bytes,it reads it and prints it.Also then the line "Enter userinput " gets printed and if the user enters '1' the program continues.
    But the problem is this program given above. If i try to send data from server stating "success"(meaning the data has been converted from bytes to String successfully) then the program stucks and the cursor doesnt go below the line which are in comments "This line doesnt get printed".There is no error printed and none of the program terminates.I am new to socket programming and dont understand much about networking.
    Any help will be truly appreciated.

  2. #2
    maddy14 is offline Member
    Join Date
    May 2013
    Posts
    25
    Blog Entries
    1
    Rep Power
    0

    Default Re: not able to send byte array from server to client

    Can someone pls assist me?Till now I have found out the only problem is when the clientconverts the inputstream into byte array.That is the line which is causing problem.IF i dont convert inputstream in bytes the program runs fine.
    Last edited by maddy14; 06-27-2014 at 09:56 AM.

  3. #3
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,090
    Rep Power
    6

    Default Re: not able to send byte array from server to client

    You forgot to pay the license fee so now you're on the free license, which means you have to wait three days for an answer.
    SurfMan likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  4. #4
    maddy14 is offline Member
    Join Date
    May 2013
    Posts
    25
    Blog Entries
    1
    Rep Power
    0

    Default Re: not able to send byte array from server to client

    Quote Originally Posted by gimbal2 View Post
    You forgot to pay the license fee so now you're on the free license, which means you have to wait three days for an answer.
    ohh ..is it?but i have never paid the license fee and i am not using this site for the first time.I have received answers in a few minutes

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,090
    Rep Power
    6

    Default Re: not able to send byte array from server to client

    ... I was kidding of course. You need to have more patience, there are only a few people in this forum actually answering questions, they are on different timezones and I can't speak for all, but most will be answering questions while at work. Meanwhile, spend more time on the problem yourself, just because you started a thread does not mean that it is now your right to demand an answer here. Its all on a volunteer basis, nobody is getting paid here. In that respect you might want to tone it down a little as coming in here stating "what is wrong with this forum, assist me" is not going to motivate people.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: not able to send byte array from server to client

    Quote Originally Posted by maddy14 View Post
    whats wrong with this forum?no one anwering..I am sure we have senior programmers here who could definately solve my issue
    When you posted your first post I was still in bed.
    When you posted this one I was packing the car.
    When you posted your next one I'd just got into work.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    maddy14 is offline Member
    Join Date
    May 2013
    Posts
    25
    Blog Entries
    1
    Rep Power
    0

    Default Re: not able to send byte array from server to client

    I am sorry.I know people voluntarily answer here n dont get paid for it.Its just that I have never waited for an answer for so long ..

  8. #8
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    988
    Rep Power
    2

    Default Re: not able to send byte array from server to client

    "waited so long?" A whole whopping 43 minutes??

    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: not able to send byte array from server to client

    Anyway, to get down to your problem, based on your OP the code is stopping in the following:
    Java Code:
    byte[] data = IOUtils.toByteArray(in);
    So...what is that class and what happens in that code?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    maddy14 is offline Member
    Join Date
    May 2013
    Posts
    25
    Blog Entries
    1
    Rep Power
    0

    Default Re: not able to send byte array from server to client

    This just converts inputstream to bytes.I have tried using while loops like dis for converting inputstream to bytes
    while ((count = is.read(bytes)) > 0) {
    bos.write(bytes, 0, count);
    }

    But then the program gets stuck at this line.If i dont convert inputstream to bytes at client side the entire program runs smoothly.I dont get it ,what should be the problem with converting inputstream to bytes

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: not able to send byte array from server to client

    It's the server that's locking up waiting for data from the client.
    That's the root cause.
    Which leads me to look at your output stream from the client.
    Which is not closed or flushed before you have the client try and read the input stream...which doesn't receive anything as the server is waiting for more input from the (as yet) unfinished transmission from the client.

    That's my current best guess.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  12. #12
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,090
    Rep Power
    6

    Default Re: not able to send byte array from server to client

    Its a blocking I/O environment, so its not surprising that at some point one of the end points is going to be waiting for more data. You need to 'know' how many bytes to receive. A common strategy is to just communicate that information first, like this SO thread demonstrates:

    sockets - how to send an array of bytes over a TCP connection (java programming) - Stack Overflow

    Then you can read a specific number of bytes in stead of "reading until there is nothing more to read"; in a blocking I/O environment that moment never comes unless the connection is closed.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: not able to send byte array from server to client

    Or there's that...;)
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  14. #14
    maddy14 is offline Member
    Join Date
    May 2013
    Posts
    25
    Blog Entries
    1
    Rep Power
    0

    Default Re: not able to send byte array from server to client

    So how do you suggest me to solve it.I tried inserting flush() statements after reading from server and writing from client is over.
    I changed out.write("any msg".getBytes()); to out.write("any msg".getBytes(),0,"any msg".length).Similarly i made that change in server code.Nothing works..

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default Re: not able to send byte array from server to client

    Re-read gimbals post.
    It's far more valid than mine.
    You need to identify your message so the receiver knows when it has read it all.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  16. #16
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,090
    Rep Power
    6

    Default Re: not able to send byte array from server to client

    Sorry, I have nothing more to offer. If it ain't working, you did something wrong. Try to figure it out, I mean there is at most an hour between my post and yours. That's not a lot of time to spend on a complex piece of programming such as this. If you can't work it out with your own code, find more examples to compare your code to. To illustrate, I found the above link by googling "java io transmit byte array".
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  17. #17
    maddy14 is offline Member
    Join Date
    May 2013
    Posts
    25
    Blog Entries
    1
    Rep Power
    0

    Default Re: not able to send byte array from server to client

    Hey thanks a lot guys for your help.Now The program is working as per the needs i guess.I focused on what you said gimbal2 and Tolls.I passed the length of bytes from client to server and now the server made byte array of size available to DataInputStream.I have posted my Server and Client codes in case somone gets stuck like me.I truly appreciate your help.

    Client
    Java Code:
    public class Client {
    	public static void main(String args[]) throws IOException
    	{
    		int userinput =1;
    		while(userinput==1)
    		{
    			String serverName = "192.168.0.8";
    			int port = 4003;
    			try
    			{
    				System.out.println("Connecting to " + serverName
    						+ " on port " + port);
    				Socket client = new Socket(serverName, port);
    				System.out.println("Just connected to "
    						+ client.getRemoteSocketAddress());
    				OutputStream outToServer = client.getOutputStream();
    				DataOutputStream out =
    						new DataOutputStream(outToServer);
    				System.out.println("above out.wirte()");
    				out.write("any msg".getBytes(),0,"any msg".length());
    				out.flush();
    				outToServer.flush();
    				InputStream inFromServer = client.getInputStream();
    				DataInputStream in =
    						new DataInputStream(inFromServer);
    				ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    
    				int nRead;
    				//byte[] data = new byte[16384];
    				//in.read(data);
    				System.out.println("converting array "+in);
    
    				byte[] data = IOUtils.toByteArray(in);
    				String msgfromserver = new String(data);
    				System.out.println("mstg from server "+msgfromserver);
    				in.close();
    				out.close();
    
    				inFromServer.close();
    				outToServer.close();
    
    
    				client.close();
    			}catch(IOException e)
    			{ 
    				e.printStackTrace();
    			}
    			System.out.println("Enter userinput ");
    			DataInputStream dis = new DataInputStream(System.in);
    			String s = dis.readLine();
    			userinput = Integer.parseInt(s);
    		}
    	}
    
    }
    Server

    Java Code:
    public class Server extends Thread
    {
    	private ServerSocket serverSocket;
    
    	public Server(int port) throws IOException
    	{
    		serverSocket = new ServerSocket(port);
    		//serverSocket.setSoTimeout(100000);
    	}
    
    	public void run()
    	{
    		while(true)
    		{
    			try
    			{
    				System.out.println("Waiting for client on port " +
    						serverSocket.getLocalPort() + "...");
    				Socket server = serverSocket.accept();
    				System.out.println("Just connected to "
    						+ server.getRemoteSocketAddress());
    				byte Message[]=null;
    				DataInputStream in =
    						new DataInputStream(server.getInputStream());
    
    				System.out.println(server.getInputStream());
    				ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    
    				int nRead=0;
    				byte[] data = new byte[in.available()];
    				System.out.println("outside while loop");
    				in.read(data);
    				/*while (nRead < in.available()) {
    					buffer.write(data, 0, nRead);
    					nRead++;
    				}*/
    				System.out.println("completed whie loop");
    				/*buffer.flush();
    
    				data= buffer.toByteArray();*/
    				
    				/*  for (int i=0;i<length;i++) {
            	   {     
            	    byte temp= in.readByte();
            	    Message[i]=temp;
            	   }
            	  }*/
    				System.out.println(data);
    				
    				String convertmsg = new String(data);
    				System.out.println("Msg converted "+convertmsg);
    				/*String tempoutput ="firstindex|msgafterwards";//in.readUTF();
    
    				System.out.println(tempoutput);
    				int posfirstpipe = tempoutput.indexOf('|');
    				tempoutput = tempoutput.substring(0,posfirstpipe);*/
    				System.out.println("above dataoutputstream");
    				DataOutputStream out =
    						new DataOutputStream(server.getOutputStream());
    				System.out.println("below dataoutputstream");
    				out.write("Success".getBytes(), 0, "Success".length());
    				server.getOutputStream().flush();
    				server.getInputStream().close();
    				//server.getOutputStream().close();
    				in.close();
    				out.close();
    				server.close();
    			}catch(SocketTimeoutException s)
    			{
    				System.out.println("Socket timed out!");
    				break;
    			}catch(IOException e)
    			{
    				e.printStackTrace();
    				break;
    			}
    		}
    	}
    	public static void main(String [] args)
    	{
    		int port = 4003;// Integer.parseInt(args[0]);
    		try
    		{
    			Thread t = new Server(port);
    			t.start();
    		}catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
    Last edited by Tolls; 06-27-2014 at 02:46 PM. Reason: fix code tags

  18. #18
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,090
    Rep Power
    6

    Default Re: not able to send byte array from server to client

    Good job!
    maddy14 likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  19. #19
    maddy14 is offline Member
    Join Date
    May 2013
    Posts
    25
    Blog Entries
    1
    Rep Power
    0

    Default Re: not able to send byte array from server to client

    Theres a problem in the above code.
    The client sometimes send the data properly to server where as sometimes it doenst send any data to server.Please help me to solve that problem

Similar Threads

  1. Replies: 5
    Last Post: 02-28-2011, 10:42 AM
  2. sending byte from server to C client
    By rnvrnv in forum Networking
    Replies: 11
    Last Post: 07-02-2010, 03:20 PM
  3. send bytes from client to server
    By 0xHexaDecimal in forum Networking
    Replies: 41
    Last Post: 06-04-2010, 02:17 PM
  4. Replies: 2
    Last Post: 03-16-2010, 07:01 AM
  5. how to send mp3 file from server to client
    By Jigga008 in forum Networking
    Replies: 0
    Last Post: 12-01-2009, 12:02 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •