Reputation: 305
I'm trying to communicate from a Lisp script to another program by using TCP/IP sockets (with sbcl and the usocket library in a Linux system). Through some online sources I have managed to put together the following simple code:
(require 'asdf)
(require 'usocket)
(defun start-client (message)
"Connects to server."
(usocket:with-client-socket (socket stream "0.0.0.0" 30000)
(format stream message)
(force-output stream)))
(start-client "Hello!~%")
This code lets me send a message, (I have tested it and it works). My problem is that I need to split this code in two different functions, one for opening the socket connection and another to send different messages at different times. Also I need to add an additional function to receive messages from the other program. However, as I'm quite new with Lisp I have failed to do so.
Upvotes: 1
Views: 1237
Reputation: 51501
The best way (I think) would be to have your entire script in the scope of with-client-socket
. You might have something like a main
function where this would fit. This avoids resource leaks. You might want to use a dynamic variable to avoid passing the socket stream manually through function arguments to wherever it is needed.
Otherwise, you have to manage the closing of the socket yourself. Any call path that might lead to program termination needs to be protected by some unwind-protect
that closes the socket using usocket:socket-close
. For that, you open the socket using usocket:socket-connect
with the same arguments as you used for usocket:with-client-socket
. (You can take a look at the source for usocket:with-client-socket
and usocket:with-connected-socket
to see the interactions taking place.)
In order to be able to write to the socket stream (obtainable through (usocket:socket-stream socket)
) and close the socket, you need to remember it somewhere, e. g. by binding a dynamic variable.
Upvotes: 2