• Stars
    star
    14
  • Rank 1,388,105 (Top 29 %)
  • Language
    Scala
  • License
    MIT License
  • Created almost 10 years ago
  • Updated almost 10 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple net test client/server for Netty and Scala lovers

This Scala library is convenient for creating network server and client, useful for quickly writing server and client tests. This library doesn't try to be robust. If you want long running robust server or client, you should try other things.

This library is small, the only dependency is Netty.

Features

HTTP:

  • Server. Server can start at random open port, very useful for tests. It also automatically handles "Expect 100 Continue" requests.
  • Client.
  • Can handle chunks up to 16 MB.
  • HTTPS.

TCP:

  • Server.
  • Client.

Be familiar with Netty

Netcaty Scaladoc

To create and inspect requests/responses, you should be familiar with things in package io.netty.handler.codec.http and io.netty.buffer in Netty Javadoc.

req and res in the examples below are:

HTTP server

Start server at port 9000:

netcaty.Http.respondOne(9000, { case (req, res) =>
  // res is an empty 200 OK response.
  // Modify it to respond what you want.
})

respondOnce returns after the port has been bounded so you don't need to manually call Thread.sleep(someTime) to wait for the server to be started. The server runs on a separate thread. It sends only one response and after that stops immediately.

If you don't want to stop the server after one response:

val server = netcaty.Http.respond(9000, { case (req, res) =>
  // res is an empty 200 OK response.
  // Modify it to respond what you want.
})

// Later:
server.stop()

Port 0 means Netcaty will start server at a random open port. This is very useful for writing tests. To get the real port, call server.getPort.

HTTP client

Sync mode:

// Create a FullHttpRequest
import io.netty.handler.codec.http.{DefaultFullHttpRequest, HttpMethod, HttpVersion}
val req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/path")

// req will be automatically released
val res = netcaty.Http.request("localhost", 9000, req)

// Use res
...

// Must manually release after using
res.release()

Async mode:

// Create a FullHttpRequest
import io.netty.handler.codec.http.{DefaultFullHttpRequest, HttpMethod, HttpVersion}
val req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/path")

// req and res will be automatically released
netcaty.Http.request("localhost", 9000, req, { res =>
  ...
})

TCP server

You must know beforehand the length of the request. In a controlled environment like tests, that's not a big drawback.

To listen on port 9000, receive exactly 123 bytes, then respond:

netcaty.Tcp.respondOne(9000, 123, { requestBytes =>
  // Return bytes to respond
  "Hello World".getBytes
})
val server = netcaty.Http.respond(9000, 123, { requestBytes =>
  // Return bytes to respond
  "Hello World".getBytes
})

// Later:
server.stop()

TCP client

You must know beforehand the length of the response. In a controlled environment like tests, that's not a big drawback.

Sync mode:

val responseBytes = netcaty.Tcp.request("localhost", 9000, requestBytes)

Async mode:

netcaty.Tcp.request("localhost", 9000, requestBytes, { responseBytes =>
  ...
})

HTTPS and TCP over SSL

In the above examples, just replace netcaty.Http and netcaty.Tcp with netcaty.Https and netcaty.Tcps.

  • Server: uses dummy certificate.
  • Client: acepts all certificates.

Use with SBT

Supported Scala versions: 2.10.x, 2.11.x

libraryDependencies += "tv.cntt" % "netcaty" %% "1.4"

Netcaty uses Netty 4. Javassist can boost Netty 4 speed. Optionally, you can add:

libraryDependencies += "org.javassist" % "javassist" % "3.18.2-GA"

Netcat

For more simple problems, maybe you don't need to use additionaly library. You can use Netcat, like this:

import scala.sys.process._

object Http {
  def async(fun: => Unit) {
    val t = new Thread(new Runnable { def run { fun } })
    t.start()
  }

  //----------------------------------------------------------------------------

  def serveRaw(port: Int, lines: Seq[String]) {
    val raw = lines.mkString("\r\n")
    (Seq("echo", "-n", raw) #| Seq("sh", "-c", "nc -l " + port)).!
  }

  def serveContent(port: Int, contentType: String, content: String) {
    val contentLength = content.getBytes.length
    serveRaw(port, Seq(
      "HTTP/1.1 200 OK",
      s"Content-Type: $contentType",
      s"Content-Length: $contentLength",
      "",
      content
    ))
  }

  def asyncServeRaw(port: Int, lines: Seq[String]) {
    async { serveRaw(port, lines) }
  }

  def asyncServeContent(port: Int, contentType: String, content: String) {
    async { serveContent(port, contentType, content) }
  }

  //----------------------------------------------------------------------------

  def requestRaw(host: String, port: Int, lines: Seq[String]): String = {
    val raw = lines.mkString("", "\r\n", "\r\n\r\n")
    // "-i 1" delays 1s, slowering the tests.
    // But without it the result will be empty.
    (Seq("echo", "-n", raw) #| s"nc -i 1 $host $port").!!
  }

  def get(host: String, port: Int, path: String): String = {
    requestRaw(host, port, Seq(
      s"GET $path HTTP/1.1",
      s"Host: $host:$port"
    ))
  }
}

More Repositories

1

cleakka

Cluster memory cache based on sun.misc.Cleaner and Akka
Scala
74
star
2

SkiaOpenGLESAndroid

Android sample that uses Skia to draw on OpenGL ES 2 surface
C++
55
star
3

tsart

Presentation: Easy distributed load test with Tsung
Shell
32
star
4

mydit

MySQL to MongoDB data replicator
Scala
26
star
5

annovention

A fork of http://code.google.com/p/annovention/ that fixes bugs and removes Apache log dependency to keep the library lightweight
Java
15
star
6

openkh

OpenKH is a bliki based on Rails 3. It best suits open communities to share knowledge.
Ruby
12
star
7

ale

A thin layer above Yaws to make web development with Yaws easier
Erlang
10
star
8

redmine_daily_todos

Plugin for Redmine to write daily reports/notes
Ruby
9
star
9

android-cairogles

Like https://github.com/anoek/android-cairo, but uses OpenGL ES 2 backend
9
star
10

unity-android-back-button-plugin

Android plugin for Unity 3D to handle BACK button to display a dialog asking user if he wants to quit
Java
7
star
11

PoseEstimationForPlanarTarget

Source code from the article Pose Estimation For Planar Target by doctor Nghia
C++
7
star
12

jsg

Cross-platform JavaScript game engine for web and *native* smartphones
C++
5
star
13

khale

CMS based on Ale
Erlang
4
star
14

vpxcam

Sample streaming server based on Google libvpx
Objective-C
4
star
15

telchat-clojure

Super simple chat program in Clojure: server = JBoss Netty, clients = telnet
Clojure
4
star
16

cordova-plugin-unswipable-android-status-bar

Prevents Android status bar to be swiped down to display system quick menu
Java
3
star
17

revaler

Revaler = Ruby evaluater, a Ruby server that accepts Ruby code from remote clients (Ruby, Erlang, Java, C...), evaluates them, then sends back the results
Ruby
3
star
18

timecard

JavaScript
3
star
19

telchat-scala

Super simple chat program in Scala: server = JBoss Netty, clients = telnet
Scala
3
star
20

jerly

A port of Cherly (https://github.com/cliffmoon/cherly) for Java
C
3
star
21

vsccps

Implementation of VSCCP in Scala
Scala
2
star
22

werial

Serial port reader for Ruby on Windows
C
2
star
23

s3m

Async Servlet 3.0 framework for Scala in the style of JAX-RS and Scalatra
Scala
2
star
24

mfs

Scala
2
star
25

android

Java
2
star
26

esan

Erlang XHTML sanitizer in the white-list style
Erlang
2
star
27

cordova-plugin-intent-action

Cordova plugin to start Android intent action
Java
2
star
28

code-lock-fsm-akka

"Code Lock" Finite State Machine demo of Erlang implemented with Akka
Scala
2
star
29

rewclib

Ruby binding for EWCLIB (library to capture camera images)
Ruby
2
star
30

file2array

Ruby version of http://stackoverflow.com/questions/5679834/convert-binary-data-into-hex-string-for-c-program
Ruby
1
star
31

survisualizer

Surveillance camera viewing field visualizer
C++
1
star
32

phonegap-xiangqi

JavaScript
1
star
33

vsccpc

Clojure
1
star
34

sclart

How to start using Scala
Scala
1
star
35

tivua

Bliki written using Xitrum
Scala
1
star
36

pegs

PegJump solver
Scala
1
star
37

ios

Objective-C
1
star
38

create-react-app-electron-typescript-boilerplate

Minimum Electron boilerplate for TypeScript based on create-react-app
TypeScript
1
star
39

glasbt

Scala
1
star
40

minimal-jopenid

JOpenID with dependencies removed
Java
1
star
41

mfe

Erlang
1
star
42

covas

Covas = Cocos2d + HTML5 canvas, a JavaScript game library designed for JSG with some flavor of Cocos2d
CoffeeScript
1
star
43

forge-show

Tool to automate the process of deploying and creating screenshots/screencasts to demo your Atlassian Forge apps
JavaScript
1
star