├── .travis.yml ├── TODO.md ├── project.clj ├── test └── clj_sockets │ └── core_test.clj ├── .gitignore ├── README.md ├── src └── clj_sockets │ └── core.clj └── LICENSE /.travis.yml: -------------------------------------------------------------------------------- 1 | language: clojure 2 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | ; TODO: file bug about checker defn blowing up when there are no type-hints in an interop method call 2 | ; TODO: fully-qualified methods in non-nil-return highlight badly -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject clj-sockets "0.1.0" 2 | :description "Sockets library for Clojure" 3 | :url "http://example.com/FIXME" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :plugins [[lein-marginalia "0.8.0"] 7 | [codox "0.8.10"]] 8 | :codox {:src-dir-uri "http://github.com/atroche/clj-sockets/blob/master/" 9 | :src-linenum-anchor-prefix "L"} 10 | :dependencies [[org.clojure/clojure "1.6.0"] 11 | [org.clojure/core.typed "0.2.77"]]) 12 | -------------------------------------------------------------------------------- /test/clj_sockets/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns clj-sockets.core-test 2 | (:refer-clojure :exclude [read-line]) 3 | (:require [clojure.test :refer :all] 4 | [clojure.string :refer [split]] 5 | [clj-sockets.core :refer :all])) 6 | 7 | (deftest ^:integration create-echo-server-and-talk-to-it 8 | (let [echo-server (agent (create-server 0)) ; port 0 means choose free port 9 | port (.getLocalPort @echo-server)] 10 | (send echo-server listen) 11 | (send echo-server (fn [socket] 12 | (let [line (read-line socket)] 13 | (write-line socket line) 14 | (close-socket socket)))) 15 | (let [client (create-socket "localhost" port)] 16 | (write-line client "hello") 17 | (let [response (read-line client)] 18 | (is (= "hello" response)) 19 | (close-socket client))))) 20 | 21 | (def popular-hosts ["yahoo.com" "google.com" "wikipedia.org" "qq.com" 22 | "twitter.com" "baidu.com"]) 23 | 24 | (defn http-request-string [hostname] 25 | (format "GET / HTTP/1.1\nHost: %s\n\n" hostname)) 26 | 27 | (deftest ^:integration make-http-requests-to-popular-hosts 28 | 29 | (doseq [hostname popular-hosts] 30 | (let [socket (create-socket hostname 80)] 31 | (write-to socket (http-request-string hostname)) 32 | (let [response (read-line socket) 33 | protocol (first (split response #" "))] 34 | (is (= "HTTP/1.1" protocol)))))) 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io 3 | 4 | ### Clojure ### 5 | pom.xml 6 | pom.xml.asc 7 | *jar 8 | /lib/ 9 | /classes/ 10 | /target/ 11 | /checkouts/ 12 | .lein-deps-sum 13 | .lein-repl-history 14 | .lein-plugins/ 15 | .lein-failures 16 | .nrepl-port 17 | 18 | 19 | ### Intellij ### 20 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 21 | 22 | *.iml 23 | 24 | ## Directory-based project format: 25 | .idea/ 26 | # if you remove the above rule, at least ignore the following: 27 | 28 | # User-specific stuff: 29 | # .idea/workspace.xml 30 | # .idea/tasks.xml 31 | # .idea/dictionaries 32 | 33 | # Sensitive or high-churn files: 34 | # .idea/dataSources.ids 35 | # .idea/dataSources.xml 36 | # .idea/sqlDataSources.xml 37 | # .idea/dynamic.xml 38 | # .idea/uiDesigner.xml 39 | 40 | # Gradle: 41 | # .idea/gradle.xml 42 | # .idea/libraries 43 | 44 | # Mongo Explorer plugin: 45 | # .idea/mongoSettings.xml 46 | 47 | ## File-based project format: 48 | *.ipr 49 | *.iws 50 | 51 | ## Plugin-specific files: 52 | 53 | # IntelliJ 54 | out/ 55 | 56 | # mpeltonen/sbt-idea plugin 57 | .idea_modules/ 58 | 59 | # JIRA plugin 60 | atlassian-ide-plugin.xml 61 | 62 | # Crashlytics plugin (for Android Studio and IntelliJ) 63 | com_crashlytics_export_strings.xml 64 | crashlytics.properties 65 | crashlytics-build.properties 66 | 67 | 68 | ### Leiningen ### 69 | pom.xml 70 | pom.xml.asc 71 | *jar 72 | /lib/ 73 | /classes/ 74 | /target/ 75 | /checkouts/ 76 | .lein-deps-sum 77 | .lein-repl-history 78 | .lein-plugins/ 79 | .lein-failures 80 | .nrepl-port 81 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # clj-sockets 2 | 3 | ![Travis build](https://travis-ci.org/atroche/clj-sockets.svg?branch=master) 4 | 5 | A Clojure library wrapping Java Sockets. Because you shouldn't have to use interop to do networking. 6 | 7 | clj-sockets is synchronous. For asynchronous networking in Clojure, check out [aleph](https://github.com/ztellman/aleph) or [async-sockets](https://github.com/bguthrie/async-sockets). 8 | 9 | This library is fully annotated using [core.typed](https://github.com/clojure/core.typed). 10 | 11 | ## References 12 | 13 | * The source code is [extensively documented and made beautiful by Marginalia](http://atroche.github.io/clj-sockets/) 14 | * [API docs](http://atroche.github.io/clj-sockets/doc/clj-sockets.core.html) via Codox 15 | 16 | ## Installation 17 | 18 | Just put `[clj-sockets "0.1.0"]` in `:dependencies` in your project.clj. 19 | 20 | ## Usage 21 | 22 | ### Connecting to a server 23 | 24 | ```clojure 25 | (require '[clj-sockets.core :refer [create-socket write-to close-socket 26 | read-line read-lines write-lines]) 27 | 28 | (def socket (create-socket "google.com" 80)) 29 | => #'clj-sockets.core/socket 30 | 31 | socket 32 | => # 33 | 34 | (write-to socket "GET / HTTP/1.1\nHost: google.com\n\n") 35 | => nil 36 | 37 | (read-line socket) 38 | => "HTTP/1.1 302 Found" 39 | 40 | (read-lines socket) 41 | => ("Cache-Control: private" "Content-Type: text/html; charset=UTF-8" etc.) 42 | 43 | (close-socket socket) 44 | => nil 45 | ``` 46 | 47 | ### Creating a server 48 | 49 | ```clojure 50 | (def server (listen (create-server 9871))) 51 | ; blocks until a connection is made 52 | ; in this case I'm doing "telnet localhost 9871" from the shell 53 | => #'clj-sockets.core/server 54 | 55 | server 56 | => # 57 | 58 | (read-line server) 59 | ; blocks until a line is sent (in this case through telnet) 60 | => "hello from telnet" 61 | 62 | (write-line server "hello there, person using telnet!") 63 | => nil 64 | 65 | (close-socket server) 66 | => nil 67 | ``` 68 | 69 | 70 | ## License 71 | 72 | Copyright © 2015 Alistair Roche 73 | 74 | Distributed under the Eclipse Public License either version 1.0 or (at 75 | your option) any later version. 76 | -------------------------------------------------------------------------------- /src/clj_sockets/core.clj: -------------------------------------------------------------------------------- 1 | ;; ## A Clojure library wrapping Java Sockets 2 | 3 | ;; I noticed there were a number of projects in the Clojure ecosystem 4 | ;; using native Java sockets to work with HTTP, IRC, etc., and it seemed 5 | ;; a shame that they were all forced to use the same ugly Java interop code. 6 | ;; What if they could just write idiomatic Clojure instead? 7 | 8 | (ns clj-sockets.core 9 | "Contains all of the functions that make up the public API of this project." 10 | (:require [clojure.core.typed :as t :refer [ann]] 11 | [clojure.java.io :refer [writer reader]]) 12 | (:refer-clojure :exclude [read-line]) 13 | (:import (java.net Socket ServerSocket) 14 | (java.io BufferedWriter BufferedReader) 15 | (clojure.lang Seqable))) 16 | 17 | ;; We need to annotate these Clojure functions if we want to call them, 18 | ;; so that core.typed knows what they take as arguments and what they return. 19 | ;; Most clojure.core functions are already annotated, but some still aren't. 20 | (ann ^:no-check clojure.java.io/writer [Socket -> BufferedWriter]) 21 | (ann ^:no-check clojure.java.io/reader [Socket -> BufferedReader]) 22 | (ann ^:no-check clojure.core/line-seq [BufferedReader -> (Seqable String)]) 23 | 24 | (ann create-socket [String Integer -> Socket]) 25 | (defn create-socket 26 | "Connect a socket to a remote host. The call blocks until 27 | the socket is connected." 28 | [^String hostname ^Integer port] 29 | (Socket. hostname port)) 30 | 31 | (ann close-socket [Socket -> nil]) 32 | (defn close-socket 33 | "Close the socket, and also closes its input and output streams." 34 | [^Socket socket] 35 | (.close socket)) 36 | 37 | (ann write-to-buffer [BufferedWriter String -> nil]) 38 | (defn ^:private write-to-buffer 39 | "Write a string to a BufferedWriter, then flush it." 40 | [^BufferedWriter output-stream ^String string] 41 | (.write output-stream string) 42 | (.flush output-stream)) 43 | 44 | 45 | (ann write-to [Socket String -> nil]) 46 | (defn write-to 47 | "Send a string over the socket." 48 | [socket message] 49 | (write-to-buffer (writer socket) message)) 50 | 51 | (ann write-line [Socket String -> nil]) 52 | (defn write-line 53 | "Send a line over the socket." 54 | [socket message] 55 | (write-to socket (str message "\n"))) 56 | 57 | ; this is memoized so that we always get the same reader for 58 | ; a given socket. otherwise the temporary readers could have text 59 | ; loaded into their buffers and then never used 60 | (ann get-reader [Socket -> BufferedReader]) 61 | (def ^:private get-reader 62 | "Get the BufferedReader for a socket. 63 | 64 | This is memoized so that we always get the same reader for a given socket. 65 | If we didn't do this, every time we did e.g. read-char on a socket we'd 66 | get back a new reader, and that last one would be thrown away despite having 67 | loaded input into its buffer." 68 | (memoize (t/ann-form 69 | (fn [^Socket socket] 70 | (reader socket)) 71 | (t/IFn [Socket -> BufferedReader])))) 72 | 73 | (ann read-char [Socket -> Character]) 74 | (defn read-char 75 | "Read a single character from a socket." 76 | [socket] 77 | (let [read-from-buffer (t/ann-form 78 | (fn [^BufferedReader input-stream] 79 | (.read input-stream)) 80 | (t/IFn [BufferedReader -> Integer]))] 81 | (-> socket 82 | get-reader 83 | read-from-buffer 84 | char))) 85 | 86 | (ann read-lines [Socket -> (Seqable String)]) 87 | (defn read-lines 88 | "Read all the lines currently loaded into the input stream of a socket." 89 | [socket] 90 | (line-seq (get-reader socket))) 91 | 92 | ;; core.typed is paranoid about Java methods returning nil, but lets you 93 | ;; override that if you're fairly sure that it's not going to. 94 | (t/non-nil-return java.io.BufferedReader/readLine :all) 95 | 96 | (ann read-line [Socket -> String]) 97 | (defn read-line 98 | "Read a line from the given socket" 99 | [^Socket socket] 100 | (let [read-line-from-reader (t/ann-form 101 | (fn [^BufferedReader reader] 102 | (.readLine reader)) 103 | (t/IFn [BufferedReader -> String]))] 104 | (read-line-from-reader (get-reader socket)))) 105 | 106 | (ann create-server [Integer -> ServerSocket]) 107 | (defn create-server 108 | "Initialise a ServerSocket on localhost using a port. 109 | 110 | Passing in 0 for the port will automatically assign a port based on what's 111 | available." 112 | [^Integer port] 113 | (ServerSocket. port)) 114 | 115 | (t/non-nil-return java.net.ServerSocket/accept :all) 116 | (ann listen [ServerSocket -> Socket]) 117 | (defn listen 118 | "Waits for a connection from another socket to come through, then 119 | returns the server's now-connected Socket." 120 | [^ServerSocket server-socket] 121 | (.accept server-socket)) 122 | 123 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | --------------------------------------------------------------------------------