954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem with remote applications interaction using URL

Hello everyone, beforehand, sorry for my english...
I have to do client - server application. They must interact, using classes URL, URLConnection. I understand, how to send data to server. But I can not realize server work.
The common algorithm of server is:
1. Start.
2. Wait for connection.
3. After receiving connection it must process request.
4. Or back for "2" or exit.

as I understand, client code to send request is:

URL url = new URL ("http://" + host + ":" + port);
            URLConnection c = url.openConnection();
            c.setDoOutput(true);
            c.connect();
            
            OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
            out.write(URLEncoder.encode(request,"UTF-8") );
            out.flush();
            out.close();

please help with server code to catch this connection?

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

Please, at least somebody!
Any help at all would be greatly appreciated!

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

here ya go, just needs slight modification on response and your listening ports

http://www.codeproject.com/KB/IP/tcpclientserver.aspx

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

sorry, forgot it was java, here's a sample java tcplistener

http://www.koders.com/java/fid857615100E60AA30093DF6D87C3135D7AE75C4F5.aspx

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

Yeah ... THANKS... IT WORKS (almost). So I have another problem:
server catches the client connections, but when I'm trying to read from InputStream

BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));

	//....
	
	String line;
        while ((line = is.readLine()) != null)       
	{
            
        	request += "\n" + line;
        }

it reads information:
"
POST / HTTP/1.1
Connection: close
Keep-Alive: 300
User-Agent: Java/1.6.0_07
Host: localhost:2604
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-type: application/x-www-form-urlencoded
Content-Length: 38

key1=search%09StudentRecBook%09123"
and after that stops at

while ((line = is.readLine()) != null)

like waiting for reading something else from stream.
What he is waiting for? Help :)

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

i don't think it will return null, until the socket gets closed

not for sure if this is the terminator, but did you check for "." (period) with crlf?

also check -1

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

I already tried -1 - same. And I took "null" from java help
java.​io.​BufferedReader
public String readLine() throws IOException
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Can you tell what you mean as period?

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

nm, think i was thinking of something else

can you please post the server and client code, at least the guts part where its sending and receiving

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

Server:

private Socket socket = null;
private BufferedReader is = null;
private PrintWriter os = null;
private String request = "";
private ServerSocket ss = null;
private int port = 2604;

public void run()
    {
        try
        {

            String line;
            while ((line = is.readLine()) != null) {
                request += "\n" + line;
            }
                        
            System.out.println("Request from ctient: " + request);
            System.out.println("Processing...");
            String msgToReport = AnalyzeEntryRequest(request);
            System.out.println("Sending: " + msgToReport);
            os.println(msgToReport);
            os.flush();
        }
        catch (IOException e)
        {
            System.out.println("Ошибка ввода-вывода. " + e);
        }
        finally
        {
            try
            {
                is.close();
                os.close();
                socket.close();
                System.out.println("Клиент " + socket + " отсоединен.");
            }
            catch (IOException e)
            {
                System.out.println("Ошибка закрытия сокетов. " + e);
            }
        }
    }
private boolean InitServer()
    {
        boolean res = true;
        
        try
        {
            is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            os = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
        }
        catch (IOException e)
        {
            System.out.println("Ошибка создания потоков. " + e);
        }
        new  Thread (this).start();
        System.out.println("Запуск сервера.");

        return res;
    }


Client:

private String sendRequest(String request)
    {
        String result = "";
        this.host = jTextField7.getText();
        InputStream in = null;
        OutputStreamWriter out = null;
        try
        {
            URL url = new URL ("http://" + host + ":" + port);
            URLConnection c = url.openConnection();
            c.setDoOutput(true);
            c.connect();
            
            out = new OutputStreamWriter(c.getOutputStream());

            String data =  URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode(request, "UTF-8") + "\r\n\r\n";
            
            out.write(data);            
            out.flush();

            out.close();
            
            BufferedReader rd = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) 
	    {
            
                result += "\n" + line;
            }

            in.close();
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(jTextPane1,"Ошибка передачи данных. " + e);
        }
        
        return result;
    }

There was no case in which server send response and client recieves it. So It can be mistakes there...

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

oops.. sorry for russian messages. It is only messages like "Server started" or "IO error". If it necessary I can translate it... :)

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

sorry don't have time to debug it right now,
are you getting an ioexception in the server from the first trycatch?

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

sorry to bombard you with links, but here is another server example

http://fragments.turtlemeat.com/javawebserver.php

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

Thanks I'll try...

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

and also just to make sure you aren't running client and server on the same machine are you?

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 
and also just to make sure you aren't running client and server on the same machine are you?

I have never had trouble running a server and client on the same machine before, but I haven't looked through the code here to see if they are doing anything different than I usually do. However in an earlier post the OP postedit reads information:
"
POST / HTTP/1.1
Connection: close
Keep-Alive: 300
User-Agent: Java/1.6.0_07
Host: localhost:2604
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-type: application/x-www-form-urlencoded
Content-Length: 38
Looking at where it says Host: localhost:2604 led me to believe it is being run on the same machine.

jasimp
Senior Poster
3,623 posts since Aug 2007
Reputation Points: 533
Solved Threads: 53
 

ah hah, forgot to look at the previous post, i've had some trouble, normally not, but sometimes yes, just want to try and eliminate all possibilities

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

Oh ... it never ends :( Thanks a lot for spending time working with me and my problem. I have tried new variant - same trouble. I found the way to pass through this problem:
I add "\n\n" in the end of request and then when reading from stream I'm checking, if the string ends on "\n\n" i break the cycle.
Here is updated server code (reading part):

while (true)
            {
                int b = is.read();
                if (b == -1)
                    break; 
                request += (char)b;
                if(request.endsWith("\n\n"))
                    break;
            }

It is workibg!
Just interesting, what is wrong? Have any ideas what is that? :)

P.S. about client and server on same machine: this is 3rd home work. Previous 2 also used interacting remote and I tested them on my machine and all works normally.

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

lol it is working and you are asking what is wrong?

what part doesn't work? or you mean why it didn't work before?

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

Yeah ... I mean before. I've posted code for case, if someone be interested.

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

i believe its because you have to "tell" the server when you are done sending, since you want the server to send the request back you have to say i'm done, now send the information

dickersonka
Veteran Poster
1,175 posts since Aug 2008
Reputation Points: 130
Solved Threads: 143
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You