segunda-feira, 23 de julho de 2007

Sockets and Caché

Some days ago, at Caché´s google groups, someone asked how to use sockets in Caché. I also have never used sockets directly in Caché, I thought it would be nice to find out how to. As I frequently say, Caché documentation is far from good docs, as Sun´s javadocs, therefore, a lot of things I discovered was through "feeling" and suppose-test-check cycles, although in this specific case, it was a bit easy.

Below, the example code I have posted in google groups. You can put this methods in any class, so you can test yourself:


ClassMethod connect()
{
set sock = ##class(%IO.Socket).%New()
set st = $$$OK

w "Starting", !

// connecting, param:
// address, port, timeout, status
w sock.Open("127.0.0.1","7777",-1, st), !
w st, !

// reading from socket, param:
// maxStringSize, timeout, status, lineTerminator
w sock.ReadLine(50, 30, st, $c(13)), !

// writing to socket, param:
// stringToBeWritten, automaticFlush, status
d sock.Write("We are the champions", 1, st)

quit
}

//===================================================

ClassMethod server()
{
set sock = ##class(%IO.ServerSocket).%New()
set st = $$$OK

w "Starting server...", !

// open serverSocket, param:
// port, timeOut, status
w sock.Open(7777, -1, st), !
w st, !

// server to listen incoming connections, param:
// timeOut, status
w sock.Listen(-1, st), !
w st, !

// writing to socket, param:
// stringToBeWritten, automaticFlush, status
d sock.Write("I am the champion", 1, st)

// reading from socket, param:
// maxStringSize, timeout, status, lineTerminator
w sock.ReadLine(50, 30, st, $c(13)), !

w sock.Close(), !

w "Closing server...", !
}


The first method, connect(), uses a %IO.Socket, which implements a basic client socket. If you are familiar to Java, you'll realize this class is very simple to use. Actually, after you create the object, you can just cal method Open, with the host´s address and port, a timeout (-1 at the example means no timeout at all) and a status object as parameters.

After connected, you can use methods from %IO.DeviceStream (which %IO.Socket inherits), to read/write data stream.

//===================================================

The second method show above, server(), uses a %IO.ServerSocket. The difference is that ServerSocket implements a server, i.e., a socket that keeps listening requests, and IO.Socket connects to a ServerSocket. Unlike Java´s ServerSocket, which returns a Socket object, %IO.ServerSocket can be used as an ordinary socket. We can see that the same methods are used to write/read to/from both socket objects.

It is also possible to keep the ServerSocket listening, and when a connection is attempted, start other job in background, to handle the new connection. I will explore this in some future post.

0 comentários: