source: project/wiki/Communicating over a unix socket, using the socket egg @ 27262

Last change on this file since 27262 was 27262, checked in by dreamtime, 8 years ago

Created page

File size: 2.5 KB
Line 
1== Communicating over a unix socket, using the socket egg
2
3Here is a short, simple example of how you can communicate over a unix socket, using the [[egg/socket|socket]] egg.
4
5'''NOTE''': Please start the server before starting the client.
6
7If the server has not been started first, the client will fail with this error:
8
9  "Error: (socket-connect) cannot initiate connection - No such file or directory"
10
11Naturally, in a real program you'd want to catch this and other potential errors, and perhaps do some fancy stuff like negotiate the message length, do partial reads with buffers, etc.  All of this has been omitted from this example for the sake of clarity, focusing on doing just the bare minimum needed for low-level communication via unix sockets.
12
13If you'd prefer a higher level interface, you may want to consider using [[egg/socket#io-ports|I/O ports]] from the socket egg, or using the [[egg/unix-sockets|unix-sockets]] egg.
14
15Server code:
16
17<enscript highlight=scheme>
18;;; A short example of a server using unix sockets and the socket egg.
19
20(use socket)
21
22;;; Create a new unix socket:
23(let ((unix-socket (socket af/unix sock/stream))
24      (backlog 1) ; Length of connection queue for socket-listen call below
25      (socket-pathname "foo")) ; Where to bind the socket to
26  ;; Bind the file to the socket:
27  (socket-bind unix-socket (unix-address socket-pathname))
28  ;; Listen for incoming connections:
29  (socket-listen unix-socket backlog)
30  ;; Read and display a message from the client.
31  (let* ((connected-socket (socket-accept unix-socket))
32         (message-length 14) ; We must know the length in advance, or negotiate it.
33         (received-data (socket-receive connected-socket message-length)))
34    ;; Report what was read:
35    (printf "Data received from the client: '~A'~%" received-data)
36    ;; Cleanup:
37    (socket-close connected-socket)
38    (socket-close unix-socket)
39    (delete-file socket-pathname)))
40</enscript>
41
42Client code:
43
44<enscript highlight=scheme>
45;;; A short example of a client using unix sockets and the socket egg.
46
47(use socket)
48
49;;; Create a new unix socket:
50(let* ((unix-socket (socket af/unix sock/stream))
51       (pathname "foo") ; Where to bind the socket to
52       (message-to-send "this is a test")) ; What to send to the server
53  ;; Bind the file "foo" to the unix socket:
54  (socket-connect unix-socket (unix-address pathname))
55  (let ((number-of-bytes-sent (socket-send unix-socket message-to-send)))
56    (printf "Number of bytes sent to the server: ~A~%" number-of-bytes-sent))
57  ;; Cleanup:
58  (socket-close unix-socket))
59</enscript>
Note: See TracBrowser for help on using the repository browser.