CHAPTER 6: External Communication Tools Socket object 195
incoming connections and then return immediately. If there is a connection request, the call to poll()
would return another
Socket object containing the brand new connection. Use this connection object to
talk to the calling client; when finished, close the connection and discard the connection object.
Before a
Socket object is able to check for an incoming connection, it must be told to listen on a specific
port, like port 80 for HTTP requests. Do this by calling the
listen() method instead of the open()
method.
The following example is a very simple Web server. It listens on port 80, waiting until it detects an
incoming request. The HTTP header is discarded, and a dummy HTML page is transmitted to the caller.
conn = new Socket;
// listen on port 80
if (conn.listen (80)) {
// wait forever for a connection
var incoming;
do incoming = conn.poll();
while (incoming == null);
// discard the request
conn.read();
// Reply with a HTTP header
incoming.writeln ("HTTP/1.0 200 OK");
incoming.writeln ("Content-Type: text/html");
incoming.writeln();
// Transmit a dummy homepage
incoming.writeln ("<html><body><h1>Homepage</h1></body></html>");
// done!
incoming.close();
delete incoming;
}
Often, the remote endpoint terminates the connection after transmitting data. Therefore, there is a
connected property that contains true as long as the connection still exists. If the connected property
returns false, the connection is closed automatically.
On errors, the
error property of the Socket object contains a short message describing the type of the
error.
The
Socket object lets you easily implement software that talks to each other via the Internet. You could,
for example, let two Adobe applications exchange documents and data simply by writing and executing
JavaScript programs.
Chat server sample
The following sample code implements a very simple chat server. A chat client may connect to the chat
server, who is listening on port number 1234. The server responds with a welcome message and waits for
one line of input from the client. The client types some text and transmits it to the server who displays the
text and lets the user at the server computer type a line of text, which the client computer again displays.
This goes back and forth until either the server or the client computer types the word “bye”.
// A simple Chat server on port 1234
function chatServer() {
var tcp = new Socket;
// listen on port 1234
writeln ("Chat server listening on port 1234");
if (tcp.listen (1234)) {
for (;;) {
Comentários a estes Manuais