echo server on Emacs

エコーサーバーをEmacs Lispで作ったやつ。
それだけなので特に面白くもないです。
HTTPDのひな型くらいにはなるかな(。´・ω・)?

;;; -*- lexical-binding: t -*-
;;
;; mode funtions
(defvar echo-server-mode-map nil)
(defvar echo-server-process nil)
(if echo-server-mode-map
    nil
  (setf echo-server-mode-map (make-sparse-keymap))
  (define-key echo-server-mode-map "\C-m" 'echo-server-send)
  (define-key echo-server-mode-map "Mouse-2" 'echo-server-send))

(defun echo-server-mode ()
  "echo server mode

\\C-m : echo-server-send"
  (interactive)
  (kill-all-local-variables)
  (use-local-map echo-server-mode-map)
  (setf mode-name "Echo Server"
	major-mode 'echo-server-mode)
  (run-hooks 'echo-server-mode-hook))

(defun echo-server-send ()
  "Send data to Serial"
  (interactive)
  (save-excursion
    (let ((sendstring))
      (goto-char (point-max))
      (setf sendstring (read-from-minibuffer "Send: "))
      (process-send-string echo-server-process (format "%s\n" sendstring)))))

(defun echo-get-buffername-from-process-name (str)
  "Return Process Buffer Name from Process name.

ex. from following
Echo-Server-30000 <127.0.0.1:1791>

-> returns: Echo-Server-30000"
  (replace-regexp-in-string " <.*$" "" str))

(defun echo-get-portnum-from-process-name (str)
  "Return Port Number from Process name.

ex. from following
Echo-Server-30000 <127.0.0.1:1791>

-> returns: 1791"
  (replace-regexp-in-string "^.*:\\(.*\\)>$" "\\1" str))

(defun echo-filter (proc string)
  "Echo Server communication filter (callback function)"
  (let ((buffername (echo-get-buffername-from-process-name (process-name proc)))
	(portno (echo-get-portnum-from-process-name (process-name proc))))
    (with-current-buffer buffername
      (goto-char (point-max))
      (insert (format "Received(local port number:%5s): %s\n" portno string))
      (process-send-string proc string)
      (insert (format "Sent (local port number:%5s): %s\n" portno string)))))

(defun echo-start-server (port)
  "Start Echo Server."
  (interactive "nServer Port Number=")
  (let* ((proc-name (format "Echo-Server-%d" port))
	 (proc)
	 (procbuf))
    (setf proc (make-network-process :name    proc-name
				     :host    'local
				     :service port
				     :type    nil
				     :nowait  t
				     :server  t
				     :filter  'echo-filter
				     ))
    (setf procbuf (get-buffer-create (process-name proc)))
    (set-process-buffer proc procbuf)
    (with-current-buffer procbuf
      (echo-server-mode)
      (make-local-variable 'echo-server-process)
      (setf echo-server-process proc))
    (display-buffer (process-buffer proc))))

(provide 'echoserver)

ソケット通信のサーバー側のアプリもEmacs Lispだとこんな感じで簡単にかけるので、通信アプリのテストを行う時なんかにEmacsが使えます。

いいなと思ったら応援しよう!