-
-
Save tomjack/e0ed6482a332826e4dcd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns com.tomojack.mine-clj.server | |
(:require [clojure.contrib.io :as io]) | |
(:import java.io.DataInputStream)) | |
(def type-parse-map {:byte '.readByte | |
:int '.readInt | |
:string '.readUTF}) | |
(def packet-handlers {}) | |
(defn parse-packet [data-in] | |
(let [packet-type (.readByte data-in) | |
handler (packet-handlers packet-type)] | |
(if handler | |
(handler data-in) | |
(throw (Exception. (str "Unknown packet type: " packet-type)))))) | |
(defn parse-packet-file [f] | |
(with-open [f-in (io/input-stream f) | |
data-in (DataInputStream. f-in)] | |
(parse-packet data-in))) | |
(defmacro defpacket [name id & fields] | |
(let [data-in-sym (gensym "data-in")] | |
`(let [parse-fn# (fn [~data-in-sym] | |
~(into {} (for [[key type] fields] | |
[key (list (type-parse-map type) data-in-sym)])))] | |
(alter-var-root #'packet-handlers assoc ~(byte id) parse-fn#)))) | |
(defpacket keep-alive 0x00) | |
(defpacket login 0x01 | |
[:player-id :int] | |
[:server-name :string] | |
[:motd :string]) | |
;; expands to | |
;; (let [parse-fn__3617__auto__ (fn [data-in3663] | |
;; {:player-id (.readInt data-in3663), | |
;; :server-name (.readUTF data-in3663), | |
;; :motd (.readUTF data-in3663)})] | |
;; (alter-var-root #'packet-handlers assoc 1 parse-fn__3617__auto__)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment