[REBOL] Re: question on the copy function and tcp ports
From: ingo:2b1 at: 28-Nov-2002 20:10
Hi Alban,
Alban Gabillon wrote:
> Hi ALL,
>
> I have a small tcp serveur
>
> port_serveur: open tcp://:8000
> forever [
> port_client: first port_serveur
> print copy port_client
> insert port_client "I am fine"
> close port_client
> ]
>
> and a small tcp client on the same machine
>
> port_client: open tcp://badeche:8000
> insert port_client "how are you"
> print copy port_client
> close port_client
>
> The copy function on the server side does work. it cannot manage to
> read the data sent by the client. I know how to solve this problem. I
> can use instead the read-io function for instance. But I do not
> understand why the copy function does not work in the server whereas it
> works in the client. Indeed If I replace the copy function with the
> read-io function in the server then the client can read the data sent by
> the server with the copy function.
It's the way network works. The copy will only return, when it is sure
to have copied _all_ data from the port. Now, how do you tell, if you've
got everything? The only way to be sure, is wait until the port is
closed. So, the copy in your server waits until the client closes port,
while the client waits until the server closes the port. A traditional
deadlock scenario.
Now, what can you do about it? Tell the server to _not_ wait until the
client has sent all the data, like this:
port_serveur: open/no-wait tcp://:8000
; CHANGES HERE! --------
forever [
port_client: first port_serveur
print copy port_client
insert port_client "I am fine"
close port_client
]
Now, the 'copy just gets what it finds in the port, and returns it. But
you don't know, if this is everything, the client sent you, just that it
is some of it.
To be sure you get everything, you need to do the copy in a loop, until
copy returns an empty string (but beware, it might be a very slow
connection, too, I guess).
port_serveur: open/no-wait tcp://:8000
; CHANGES HERE! --------
forever [
data: copy ""
port_client: first port_serveur
while [not empty? new-data: copy port_client][
append data new-data
]
print data
insert port_client "I am fine"
close port_client
]
; No changes in the client code needed
Of course, someone like Holger could have explained much better, I hope
it helped, anyway.
Ingo