Common Lisp socket编程最小实例——基于usocket

1. 服务端主要函数:socket-server

(require 'usocket)

(defpackage :myserver
  (:use :common-lisp :usocket)
  (:nicknames :mysrv)
  (:export "start-server"))

(in-package :mysrv)

(defun start-server (port)
  (socket-server "127.0.0.1" port #'(lambda (stream) (format stream "~a~%" "hello usocket"))))
该函数参考 https://common-lisp.net/project/usocket/api-docs.shtml

2. 客户端主要函数:socket-connect

(require 'usocket)

(defpackage :myclient
  (:use :common-lisp :usocket)
  (:nicknames :mycli)
  (:export "start-client"))

(in-package :myclient)

(defun start-client (ip port)
  (let ((sock (usocket:socket-connect ip port)))
    (progn
      (force-output (usocket:socket-stream sock))
      (do ((line                                                  
         (read-line (usocket:socket-stream sock) nil)             
         (read-line (usocket:socket-stream sock) nil)))
       ((not line))                                               
      (format t "~A" line)))))
该函数参考 http://common-lisp.net/project/common-lisp-beginner/sockets_doc.html

3. 测试

测试环境为emacs+slime,telnet,并假设你已经安装好quicklisp。

服务端启动后,使用telnet测试其是否可以成功运行,图示如下:

Common Lisp socket编程最小实例——基于usocket_第1张图片

客户端连接服务端,图示如下:

Common Lisp socket编程最小实例——基于usocket_第2张图片

可见,telnet和客户端都正确返回"hello usocket"这一字符串。

4. 补充

客户端发送函数:

(require 'usocket)

(defvar sock '())

(defun myclient (host port)
  (setq sock (usocket:socket-connect host port)))

(defun my-send (buf)
  (if sock
      (progn
        (format (usocket:socket-stream sock) "~A" buf)
        (force-output (usocket:socket-stream sock))
        )
      nil))

本节参照:

http://stackoverflow.com/questions/25608424/websocket-client-in-common-lisp-with-usocket-library

http://stackoverflow.com/questions/17257567/receiving-data-through-lisp-usocket

http://www.lispworks.com/documentation/HyperSpec/Body/f_finish.htm#force-output

可正常链接服务端并发送数据,请自行测试。

enjoy youself !


你可能感兴趣的:(socket,telnet,lisp,common,usocket)