| << Prev | - Up - | Next >> |
A frequently occuring situation is to have a single server with a port number known to several clients and that all these clients want to connect to that server. For this purpose sockets have the possibility to accept more than a single connection.
The first step is to create the server socket S with a port number P:
S={New Open.socket init}
P={S bind(port:$)}
{S listen} The clients can connect later to this socket with the port number P.
class Accepted from Open.socket
meth report(H P)
{Browse read(host:H port:P read:{self read(list:$)})}
{self report(H P)}
end
end
proc {Accept}
H P A
in
{S accept(acceptClass:Accepted
host:?H port:?P accepted:?A)}
thread
{A report(H P)}
end
{Accept}
endProgram 5.1: Accepting multiple connections.
How to set up the server is shown in Program 5.1. The procedure Accept waits until the server socket S accepts a connection. When a connection is accepted, the variable A is bound to a newly created object. The object A is created from the class Accepted, this is specified by the feature acceptClass. The newly created object is already connected: Applying the object to the message report(H P) waits that on the accepted connection data arrives.
The loop to accept connections is started by applying the procedure Accept:
{Accept}
Let us assume that we have two clients C1 and C2 that need to connect to the socket with port number P:
C1={New Open.socket client(port:P)}
C2={New Open.socket client(port:P)}
After the clients are connected, sending data from the clients is as usual:
{C1 write(vs:'hello from C1')}
As soon as the socket object created by the procedure Accept receives the data sent from a client, the data appears in the Browser.
| << Prev | - Up - | Next >> |