Results 1 to 13 of 13
  1. #1
    Genom is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default Getting string from network connection (Reader)

    Hi,

    I am new to java programming and I am now writing a java client which binds a server (written in .net). The problem I am facing is, that .Net's sending string in a different way. There is a header comming and then characters. I wanted to know, how java reads the incoming strings?

    I mean ObjectInputStream.ReadLine();

    Thanks a lot!

  2. #2
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Are you trying to read Objects or Strings?
    ObjectInputStream is for object serialization (send complete objects from place to place). If you just need to read something coming from the server, try either an InputStreamReader or a BufferedReader:
    Java Code:
    try {
                Socket s = new Socket("192.168.2.100", 12345);
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                
                System.out.println(in.readLine());
                
                // or manually
                
                InputStreamReader insr = new InputStreamReader(s.getInputStream());
                char[] buffer = new char[1024];
                int bytesRead = 0;
                boolean someConditionalStatement = false;
                do{
                    bytesRead = insr.read(buffer);
                    String str = new String(buffer, 0, bytesRead);
                    System.out.println(str);
                }while(someConditionalStatement);
                
            } catch (UnknownHostException ex) {
                Logger.getLogger(Misc.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Misc.class.getName()).log(Level.SEVERE, null, ex);
            }

  3. #3
    Genom is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    I didn't realize that ObjectInputStream/ObjectOutputStream was dedicated to read/send objects, as there are .readBytes .readInt etc... Thanks a lot! I am going to try with other classes.

  4. #4
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    It might be possible to use them generically like that because of their super classes - but I'm not 100% on that one.

    Do you know what protocol is being used? There are higher level classes for many protocols - like HTTP.

  5. #5
    Genom is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    Server side is using TCP protocol. But I don't see any possibility to specify TCP as protocol in my java client. By the way I tried BufferedWriter and the OutputStreamWriter:

    Java Code:
    				socket = new Socket(host,Integer.parseInt(p));
    				
    	            OutputStreamWriter insw = new OutputStreamWriter(socket.getOutputStream());
    
    	            insw.write(jtf1.getText());
    Here I am trying to send the password (server waits for a password for 10 seconds) but it doesn't reach server. I also tried sending byte/bytes. So I thought maybe my VB.Net server is the problem. So I tried the server code with a VB.Net client. It works. So there has to be some problem with my java code. Maybe I need to specify the TCP protocol Here is the full code:

    Java Code:
    //272 lines of code
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    
    
    
    class client extends JFrame implements ActionListener,Runnable
    {
    	Socket socket = null;
    	JLabel l1,l2,l3,l4,l5,l6,jtf3;
    	JTextField jtf1,jtf2,jtf4,jtf5;
    	TextArea ta;
    	InetAddress host;
    	int port = 6666;
    	Thread t = null;
    	JButton jb,jb2,jb3;
    	
    	client(String s)	
    	{
    		super(s);
    		
    		myadapter a = new myadapter(this);
    		addWindowListener(a);
    		
    		l5 = new JLabel("Enter IP : ");
    		add(l5);
    		jtf4 = new JTextField(15);
    		add(jtf4);
    		jtf4.setText("10.10.241.215");
    		
    		add(new JLabel("                          "));
    		
    		l6 = new JLabel("Enter Port : ");
    		add(l6);
    		jtf5 = new JTextField(15);
    		add(jtf5);
    		jtf5.setText("6666");
    		
    		l1 = new JLabel("Password :  ");
    		add(l1);
    		jtf1 = new JTextField(15);
    		jtf1.setText("password");
    		add(jtf1);
    		
    		jb2 = new JButton("Connect");
    		add(jb2);
    		jb2.addActionListener(this);
    		
    		jb3 = new JButton("Disconnect");
    		add(jb3);
    		jb3.addActionListener(this);
    				
    		add(new JLabel("                                        "));
    		
    		l2 = new JLabel("Message : ");
    		add(l2);
    		jtf2 = new JTextField(34);
    		add(jtf2);
    					
    		jb = new JButton("Send Message");
    		add(jb);
    		jb.addActionListener(this);
    
    		
    		l3 = new JLabel("Status : ");
    		add(l3);
    		jtf3 = new JLabel("Not connected to the server...");
    		add(jtf3);
    		
    		add(new JLabel("                                                                            "));
    				
    		l4 = new JLabel("Recieved Messages : ");
    		add(l4);
    		ta = new TextArea("",15,80);
    		add(ta);
    		ta.setFont(Font.getFont("verdana"));
    		ta.setBackground(Color.ORANGE);
    		
    
    		
    		jtf3.setText("Not connected to Server, click connect");		
    	}
    	
    	public void actionPerformed(ActionEvent ae)
    	{
    		try{
    			String str = ae.getActionCommand();
    			
    			if(str.equals("Disconnect"))
    			{
    				try
    				{
    					jb.setEnabled(false);
    					jtf2.setEditable(false);
    					jb2.setEnabled(true);
    					jb3.setEnabled(false);
    					jtf4.setEditable(true);
    					jtf5.setEditable(true);
    					socket.close();				
    					socket = null;					
    				}
    				catch(Exception e)
    				{}
    			}
    			
    			if(str.equals("Send Message"))
    			{
    					sendData();
    			
    			}
    			if(str.equals("Connect"))
    			{
    				try{
    				
    				host = InetAddress.getByName(jtf4.getText());
    				String p = jtf5.getText();
    				
    				try{
    					if(socket!=null)
    					{
    						socket.close();
    						socket = null;
    					}
    					}
    					catch(Exception e)
    					{}
    								
    				
    				socket = new Socket(host,Integer.parseInt(p));
    				
    	            OutputStreamWriter insw = new OutputStreamWriter(socket.getOutputStream());
    
    	            insw.write(jtf1.getText());
    	              
    	            
    				jtf2.setEditable(true);
    				jb.setEnabled(true);
    				jb2.setEnabled(false);
    				jb3.setEnabled(true);
    				jtf4.setEditable(false);
    				jtf5.setEditable(false);
    				
    				jtf3.setText("Connection established with Server, start chatting");
    				
    				t = new Thread(this,"Reading");
    				t.start();
    				}
    				
    			catch(Exception e)				
    			{
    				jtf3.setText("Could not connect to Server, connect again");
    			}
    			}
    			}catch(Exception e)
    			{	
    				jtf3.setText("Action Error");
    			}
    	}
    	
    	public void sendData()
    	{
    		try
    		{
    			BufferedWriter obj = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    				obj.write(jtf2.getText());
    				jtf3.setText("Message was sent successfully!");
    
    		}catch(Exception e)
    		{
    				jtf3.setText("Error occured while sending message");	
    		}
    	}
    	
    	
    public void run()
    	{
    		try
    		{
    				
    			while(true)			
    			{
    				ObjectInputStream obj = new ObjectInputStream(socket.getInputStream());
    				String msg;
    				msg=(String) obj.readUTF();
    				
    				ta.append(msg+"/n");
    				
    			}
    		
    		}
    		catch(Exception e)
    		{
    			jtf2.setEditable(false);
    			jb2.setEnabled(true);
    			jb.setEnabled(false);
    			jb3.setEnabled(false);
    			jtf4.setEditable(true);
    			jtf5.setEditable(true);
    			jtf3.setText("Connection Lost");
    		}
    	}
    
    }
    
    class demo
    {
    	public static void main(String a[])
    	{
    		client f = new client("Messenger by Kashif Khan");
    		f.setLayout(new FlowLayout());
    		f.setSize(600,425);
    		f.setResizable(false);
    		f.setVisible(true);
    	}
    }
    
    class myadapter extends WindowAdapter
    {
    	client f;
    	public myadapter(client j)
    	{
    		f = j;
    	}
    	public void windowClosing(WindowEvent we)
    	{
    		f.setVisible(false);
    		try{
    			f.socket.close();
    			f.dispose();
    			}
    			catch(Exception e)
    			{
    			}
    			System.exit(0);
    	}
    }
    P.S.: Some lines need to be changed too. I didn't change them yet and waiting until password verification works. By the way I found the code in internet. I use it as tutorial to learn network communication in java. I don't want to take the credit for the code I didn't write all alone. :)

    I also tried PrintWriter (print()) method... :(
    Last edited by Genom; 02-14-2011 at 10:12 PM.

  6. #6
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    TCP is a transport protocol. Http runs over TCP. All communications you make with java's networking libraries are TCP. TCP does not specify how data is formatted, compressed, etc..., rather it specifies how the data packages are transported. I was asking what protocol the server uses on top of TCP. For example, Http, FTP, SSH, SSL, Telnet, IRC, AIM, ICQ, etc... all run on top of TCP. If the server is not using some known protocol, then you need to know exactly how it is doing what it does.

    The server will only understand what you are asking/telling it if you provide that information in the correct format. For example, if the server was using Http, then passing a password would probably involve writing an http header complete with the resource, char encoding, server address, content-lengh, etc... and a body that might contain the password (encrypted or otherwise).

    If the server is something custom running over SSL or the like, you'd need to establish an SSL connection first, and then begin posting requests.

    When I do java networking, its usually one of the major protocols like http or BOSH, or object serialization, where I create a 'Message' class that contains all the fields I need, and perhaps some enums. That then gets serialized and sent over TCP where it is received and turned back into an object automatically on the other end.

    In your case if its some .net thing, that def. will not work as .net is not the same as java byte code. So you are limited to sending bytes to the server. In order for the bytes to do anything, they must be presenting in the correct manner. This means you must know what protocol the server is using and on what port, and how to establish a connection using that protocol.

    BOSH for example starts with a client side POST to the server over http, then the server responds with a message. The client must parse that message and reply to the server again. Subsequent message can contain data or other connection information.

  7. #7
    Genom is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    I have written server and it is listenning at a port which user defines (like in my case 6666). It accepts any connection attempt first (my java client can connect to server) than reads a string as password. If password is correct server sends another string which tells to client "Your password was correct I am listenning for further messages". If password is incorrect it closes sockets and streams and listens again in the same port. So I know that strings sent by java may not be the same string in .net. So I was only reading bytes coming from client in order to figure out, how can I convert that information into .net string. This is the next step. But so far I can't even get any bytes. Specifically my my server code is (after connection is accepted):


    Java Code:
            SocketStream = New NetworkStream(Connection)
            writer = New BinaryWriter(SocketStream)
            reader = New BinaryReader(SocketStream)
    
            Try
    
    
                'Checking for password
                Connection.ReceiveTimeout = 10000 'Password must come within 10 seconds otherwise: timeout
                Dim password As String = ""
    
                Try
                    Debug.Print(reader.ReadByte) 'Here I am trying to read the byte which works with a .net client
                Catch ex As IOException
                    Debug.Print(ex.Message)
                End Try
    
    
    
                password = reader.ReadString ' I use generally this with the .net client as they are understanding .net strings
                Debug.Print(password) 'I am trying to see "how" password is read
    
                If MyPassword = password Then  'Verification for password.
    .....
    I don't know any of those protocols I usually use simple TCP connections. (Well I know them of course but I have never used them in my applications)

  8. #8
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    A string is a string assuming your server doesn't use some crazy encoding. If you write to an outputStream (convert the string to a byte array and send that), then the server shouldn't care. If you open a packet sniffer like wireshark on the server, does the packet arrive? and if so, what are the contents? Does the server receive the message at all?

  9. #9
    Genom is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    Yes OutputStream/InputStream works! I really don't understand why other classes (like BufferedStream) didn't work. Simple Output- and Inputstream works perfect. Thanks you a lot!

  10. #10
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    No problem. A bufferedStreamReader waits for a newline character when using readline. Also, make sure you are using flush after each message you send, as things will sit in the send buffer till you call it. It is possible you never flushed, and therefor the message never left the buffer/your computer/made it to the server.

  11. #11
    Genom is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default

    You are 100% right! I didn't "flushed". Actually I now realize what flush is for. I have seen it before a lot but never used by myself.

  12. #12
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    :D Its happened to me many times! Good luck! :D

  13. #13
    Genom is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

Similar Threads

  1. Replies: 7
    Last Post: 05-02-2010, 10:35 PM
  2. Driver, Class, and Connection String to UltraLite 11
    By Harrie_KalaChakra in forum Eclipse
    Replies: 0
    Last Post: 01-06-2010, 04:33 AM
  3. Replies: 0
    Last Post: 05-31-2009, 07:11 AM
  4. How do i get connection string from struts-config.xml ?
    By Md Saim in forum Web Frameworks
    Replies: 1
    Last Post: 09-05-2008, 01:20 PM
  5. Using Applets for network connection
    By bugger in forum New To Java
    Replies: 0
    Last Post: 11-19-2007, 05:16 PM

Posting Permissions

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