Skip to content

Instantly share code, notes, and snippets.

@tomjack tomjack/server.clj Secret
Created Sep 28, 2010

Embed
What would you like to do?
(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
You can’t perform that action at this time.