Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple tcp client examples in emacs elisp?

I'm trying to learn emacs elisp and trying to write a little program to connect to a TCP/IP port and process records that come back. In one case I'll be parsing CSV data and in the another, I'll be parsing JSON (e.g. from GPSD, and json.el thankfully comes with emacs). I've looked at the echo-server example, but I'm looking for a client example that shows connecting with make-network-process and processing line oriented data. It's not http, so I can't use url-retrieve-synchronously.

My elisp skills are really weak, so I'm looking for really basic examples.

Thanks!

like image 800
Kurt Schwehr Avatar asked May 28 '11 16:05

Kurt Schwehr


1 Answers

I was looking for something a lot simpler. I've finally managed to code it from a stripped down TcpClient example. This works from the command line if you save it as client.el, do chmod +x client.el, and ./client.el. It will print out what ever the server decides to send and quit after 300 seconds. It really needs some comments to explain what it going on.

#!/usr/bin/emacs --script

(defvar listen-port 9999
    "port of the server")

(defvar listen-host "127.0.0.1"
    "host of the server")

(defun listen-start nil
    "starts an emacs tcp client listener"
    (interactive)
    (make-network-process :name "listen" :buffer "*listen*" :family 'ipv4 :host listen-host :service listen-port :sentinel 'listen-sentinel :filter 'listen-filter))

(defun listen-stop nil
  "stop an emacs tcp listener"
  (interactive)
  (delete-process "listen"))

(defun listen-filter (proc string)   
  (message string))

(defun listen-sentinel (proc msg)
  (when (string= msg "connection broken by remote peer\n")
    (message (format "client %s has quit" proc))))

(listen-start)
(sleep-for 300)
(listen-stop)
like image 157
Kurt Schwehr Avatar answered Sep 28 '22 14:09

Kurt Schwehr