Kurt Schwehr
Kurt Schwehr

Reputation: 2698

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!

Upvotes: 15

Views: 4845

Answers (3)

Kurt Schwehr
Kurt Schwehr

Reputation: 2698

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)

Upvotes: 19

jd_
jd_

Reputation: 510

If you want something more solid and with possible support of encryption for example, you should take a look at network-stream.el and proto-stream.el.

Upvotes: 5

Trey Jackson
Trey Jackson

Reputation: 74420

The Emacs wiki is a great place to look.

See TcpClient

Upvotes: 7

Related Questions