This document discusses using Leanpub to write and publish a living book. It explains that a living book is inspired by Neal Stephenson's A Young Lady's Illustrated Primer, where each chapter has a theme and pushes the subject matter to new problems. The author aims to write such a living book on Leanpub about a topic of interest, by continually adding new material until running out of content. Each chapter will be structured as an adventure to not only teach solutions to existing problems, but how to solve new ones. The document provides examples of chapter content from a Hello World book that introduces network encryption.
TechBook: EMC Compatibility Features for IBM Copy Services on z/OSEMC
This TechBook provides an introduction to EMC’s compatibility features for IBM’s Advanced Copy Services technologies. A configuration and operations compatibility quick guide for PPRC, XRC, and FlashCopy features supported by EMC is included. An overview of common deployments of Advanced Copy Services features, the degree of EMC’s compliance with those features, and EMC’s role in the deployment and operations of GDPS are discussed.
Mike Brooks
Mike’s bestselling book of phone scripts gives you the essential skills and winning techniques to help you breeze past gatekeepers, establish rapport with decision makers and close more sales.
libmc is a memcached client library for Python without any other dependencies in runtime. It's mainly written in C++ and Cython. https://github.com/douban/libmc
TechBook: EMC Compatibility Features for IBM Copy Services on z/OSEMC
This TechBook provides an introduction to EMC’s compatibility features for IBM’s Advanced Copy Services technologies. A configuration and operations compatibility quick guide for PPRC, XRC, and FlashCopy features supported by EMC is included. An overview of common deployments of Advanced Copy Services features, the degree of EMC’s compliance with those features, and EMC’s role in the deployment and operations of GDPS are discussed.
Mike Brooks
Mike’s bestselling book of phone scripts gives you the essential skills and winning techniques to help you breeze past gatekeepers, establish rapport with decision makers and close more sales.
libmc is a memcached client library for Python without any other dependencies in runtime. It's mainly written in C++ and Cython. https://github.com/douban/libmc
Borland c++ version_3.0_users_guide_1991praveen188668
dfg dfgdtyth rth kljlkdfjgd
dfk
it can be also read by c language
isurp jsjjs alksdkjd ndnn tjskje kkskskso suyldkfj .
jdkfljdklfj dfdfhgklhh peyunkjhvsoivnv sdhfdh jhuijnd dfhkjhfkndfjnknvjvdv
The first cut of a talk on the R&D process in software development, including taking an invention to patent.
Includes two sets of code examples. One is Forth implemented in a 1980s dialect of Basic.
The other introduces evolutionary prototyping using a hybrid ruby/bash methodology.
Generics, Reflection, and Efficient CollectionsEleanor McHugh
This is a talk about how we structure and collate information so as to effectively process it, the language tools Go provides to help us do this, and the sometimes frustrating tradeoffs we must make when marry the real world with the digital.
We'll start by looking at basic collection types in Go: array, slice, map, and channel. These will then be used as the basis for our own user defined types with methods for processing the collected items.
These methods will then be expanded to take functions as parameters (the higher order functional style popularised by languages such as Ruby) and by using Go's Reflection package we will generalise them for a variety of tasks and uses cases.
Reflection adds an interpreted element to our programs with a resulting performance cost. Careful design can often minimise this cost and it may well amortise to zero on a sufficiently large collection however there is always greater code complexity to manage. When the data to be contained in a user defined collection is homogenous we can reduce much of this complexity by using Generics and our next set of examples will demonstrate this.
At the end of this talk you should have some useful ideas for designing your own collection types in Go as well as a reasonable base from which to explore Reflection, Generics, and the Higher-Order Functional style of programming.
Go for the paranoid network programmer, 3rd editionEleanor McHugh
Draft third edition of my #golang network programming and cryptography talk given to the Belfast Gophers Meetup. Now with an introduction to websockets.
An introduction to functional programming with goEleanor McHugh
A crash course in functional programming concepts using Go. Heavy on code, light on theory.
You can find the examples at https://github.com/feyeleanor/intro_to_fp_in_go
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
Digital Identity talk from Strange Loop 2018 and Build Stuff Lithuania 2018 including walkthrough of the uPass system and the design principles behind it.
Don't Ask, Don't Tell - The Virtues of Privacy By DesignEleanor McHugh
This is a fairly technical overview of the considerations involved in architecting software systems to support privacy. Rather than focus on what the law demands - something which can change across time and jurisdictions - it looks at the real problems we need to solve to know as little about the users of computer systems as possible whilst achieving their needs.
Don't ask, don't tell the virtues of privacy by designEleanor McHugh
A very light intro talk on privacy, identity, and designing with the latter to preserve the former.
Probably makes no sense at all without the audio so if it whet's your appetite dig through my other decks on these topics. Most of those have code in for the more technically minded.
An overview of the uPass digital identity system. Covers the core problem domain and the end-to-end stack from liveness to black-box transaction store. Lots of diagrams, references to all the relevant patent applications and so forth.
An introduction to Go from basics to web through the lens of "Hello World", extracted from the Book "A Go Developer's Notebook" available from http://leanpub.com/GoNotebook
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
8. Create a Book
The Book
BOOK TITLE
BOOK URL
MAIN LANGUAGE USED IN THE BOOK
This helps us to set up the fonts that we use in your book. If you are writing with a mixture of languages that
includes Chinese, Japanese or Korean, then you should check out the language switcher section of the
manual. If you have troubles with characters not showing up properly, please let us know at
hello@leanpub.com.
How do you want to write?
The Next Leanpub Bestseller
bookleanpub.com/
English !
"
# $
0 "
LEANPUB
writing a book without working at it
9. LEANPUB
➤ take existing content and publish it in book form
➤ aimed at bloggers with existing articles
➤ but also works with
➤ slide decks
➤ code repos
➤ word documents
16. Hello World
It’s a tradition in programming books to start with a canonical “Hello World” example and whilst I’ve
never felt the usual presentation is particularly enlightening, I know we can spice things up a little to
provide useful insights into how we write Go programs.
Let’s begin with the simplest Go program that will output text to the console.
Example 1.1
1 package main
2
3 func main() {
4 println("hello world")
5 }
The first thing to note is that every Go source file belongs to a package, with the main package defining
an executable program whilst all other packages represent libraries.
1 package main
For the main package to be executable it needs to include a main() function, which will be called following
program initialisation.
3 func main() {
Notice that unlike C/C++ the main() function neither takes parameters nor has a return value. Whenever
a program should interact with command-line parameters or return a value on termination these tasks are
HELLO WORLD?
well… sort of…
19. WRITING A LIVING BOOK
➤ inspired by Neal Stephenson's A Young Lady's Illustrated Primer
➤ (every programmer should read The Diamond Age & Cryptonomicon)
➤ only without the interactivity
➤ pick your topic of interest
➤ keep adding new material until you run out
➤ each chapter has a theme
➤ and is structured as an adventure
➤ it should push its subject matter to breaking point
➤ so the reader doesn't only learn solutions to existing problems
➤ they learn how to solve new problems
20. Hello World
It’s a tradition in programming books to start with a canonical “Hello World” example and whilst I’ve
never felt the usual presentation is particularly enlightening, I know we can spice things up a little to
provide useful insights into how we write Go programs.
Let’s begin with the simplest Go program that will output text to the console.
Example 1.1
1 package main
2
3 func main() {
4 println("hello world")
5 }
The first thing to note is that every Go source file belongs to a package, with the main package defining
an executable program whilst all other packages represent libraries.
1 package main
For the main package to be executable it needs to include a main() function, which will be called following
program initialisation.
3 func main() {
Notice that unlike C/C++ the main() function neither takes parameters nor has a return value. Whenever
a program should interact with command-line parameters or return a value on termination these tasks are
FREE SHOULD BE USEFUL
60+ pages of Hello World examples
21. Hello World 53
16 func main() {
17 Serve(":1025", func(connection *UDPConn, c *UDPAddr, packet *bytes.Buffer) (n int) {
18 var key rsa.PublicKey
19 if e := gob.NewDecoder(packet).Decode(&key); e == nil {
20 if response, e := rsa.EncryptOAEP(sha1.New(), rand.Reader, &key, HELLO_WORLD, RSA
21 _LABEL); e == nil {
22 n, _ = connection.WriteToUDP(response, c)
23 }
24 }
25 return
26 })
27 }
28
29 func Serve(address string, f func(*UDPConn, *UDPAddr, *bytes.Buffer) int) {
30 Launch(address, func(connection *UDPConn) {
31 for {
32 buffer := make([]byte, 1024)
33 if n, client, e := connection.ReadFromUDP(buffer); e == nil {
34 go func(c *UDPAddr, b []byte) {
35 if n := f(connection, c, bytes.NewBuffer(b)); n != 0 {
36 Println(n, "bytes written to", c)
37 }
38 }(client, buffer[:n])
39 }
40 }
41 })
42 }
43
44 func Launch(address string, f func(*UDPConn)) {
45 if a, e := ResolveUDPAddr("udp", address); e == nil {
FREE SHOULD BE USEFUL
make a sound introduction to network encryption
22. Hello World 13
In the function signature we use v …interface{} to declare a parameter v which takes any number of
values. These are received by print() as a sequence of values and the subsequent call to Println(v…) uses
this same sequence as this is the sequence expected by Println().
So why did we use …interface{} in defining our parameters instead of the more obvious …string? The
Println() function is itself defined as Println(…interface{}) so to provide a sequence of values en masse
we likewise need to use …interface{} in the type signature of our function. Otherwise we’d have to create
a []interface{} (a slice of interface{} values, a concept we’ll cover in detail in a later chanpter) and copy
each individual element into it before passing it into Println().
Encapsulation
In this chapter we’ll for the most part be using Go’s primitive types and types defined in various
standard packages without any comment on their structure, however a key aspect of modern programming
languages is the encapsulation of related data into structured types and Go supports this via the struct
type. A struct describes an area of allocated memory which is subdivided into slots for holding named
values, where each named value has its own type. A typical example of a struct in action would be
Example 1.17
1 package main
2
3 import "fmt"
4
5 type Message struct {
6 X string
7 y *string
8 }
9
10 func (v Message) Print() {
11 if v.y != nil {
12 fmt.Println(v.X, *v.y)
13 } else {
14 fmt.Println(v.X)
15 }
16 }
17
18 func (v *Message) Store(x, y string) {
19 v.X = x
20 v.y = &y
21 }
22
23 func main() {
24 m := &Message{}
25 m.Print()
26 m.Store("Hello", "world")
27 m.Print()
28 }
ENCAPSULATION
package main
import "fmt"
type Message struct {
X string
y *string
}
func (v Message) Print() {
if v.y != nil {
fmt.Println(v.X, *v.y)
} else {
fmt.Println(v.X)
}
}
func (v *Message) Store(x, y string) {
v.X = x
v.y = &y
}
func main() {
m := &Message{}
m.Print()
m.Store("Hello", "world")
m.Print()
}
23. ENCAPSULATION
package main
import "fmt"
type Message struct {
X string
y *string
}
func (v Message) Print() {
if v.y != nil {
fmt.Println(v.X, *v.y)
} else {
fmt.Println(v.X)
}
}
func (v *Message) Store(x, y string) {
v.X = x
v.y = &y
}
func main() {
m := &Message{}
m.Print()
m.Store("Hello", "world")
m.Print()
}
package main
import "fmt"
type HelloWorld bool
func (h HelloWorld) String() (r string) {
if h {
r = "Hello world"
}
return
}
type Message struct {
HelloWorld
}
func main() {
m := &Message{ HelloWorld: true }
fmt.Println(m)
m.HelloWorld = false
fmt.Println(m)
m.HelloWorld = true
fmt.Println(m)
}
24. Hello World 22
Startup
One of the less-discussed aspects of computer programs is the need to initialise many of them to a pre-
determined state before they begin executing. Whilst this is probably the worst place to start discussing
what to many people may appear to be advanced topics, one of my goals in this chapter is to cover all of
the structural elements that we’ll meet when we examine more complex programs.
Every Go package may contain one or more init() functions specifying actions that should be taken during
program initialisation. This is the one case I’m aware of where multiple declarations of the same identifier
can occur without either resulting in a compilation error or the shadowing of a variable. In the following
example we use the init() function to assign a value to our world variable
Example 1.26
1 package main
2 import . "fmt"
3
4 const Hello = "hello"
5 var world string
6
7 func init() {
8 world = "world"
9 }
10
11 func main() {
12 Println(Hello, world)
13 }
However the init() function can contain any valid Go code, allowing us to place the whole of our program
in init() and leaving main() as a stub to convince the compiler that this is indeed a valid Go program.
Example 1.27
1 package main
2 import . "fmt"
3
4 const Hello = "hello"
5 var world string
6
7 func init() {
8 world = "world"
9 Println(Hello, world)
10 }
11
12 func main() {}
When there are multiple init() functions the order in which they’re executed is indeterminate so in general
it’s best not to do this unless you can be certain the init() functions don’t interact in any way. The following
happens to work as expected on my development computer but an implementation of Go could just as
easily arrange it to run in reverse order or even leave deciding the order of execution until runtime.
STARTUP
package main
import . "fmt"
const Hello = "hello"
var world string
func init() {
world = "world"
}
func main() {
Println(Hello, world)
}
25. Hello World 23
Example 1.28
1 package main
2 import . "fmt"
3
4 const Hello = "hello"
5 var world string
6
7 func init() {
8 Print(Hello, " ")
9 world = "world"
10 }
11
12 func init() {
13 Printf("%vn", world)
14 }
15
16 func main() {}
HTTP
So far our treatment of Hello World has followed the traditional route of printing a preset message to
the console. Anyone would think we were living in the fuddy-duddy mainframe era of the 1970s instead
of the shiny 21st Century, when web and mobile applications rule the world.
Turning Hello World into a web application is surprisingly simple, as the following example demon-
strates.
Example 1.29
1 package main
2 import (
3 . "fmt"
4 "net/http"
5 )
6
7 const MESSAGE = "hello world"
8 const ADDRESS = ":1024"
9
10 func main() {
11 http.HandleFunc("/hello", Hello)
12 if e := http.ListenAndServe(ADDRESS, nil); e != nil {
13 Println(e)
14 }
15 }
16
17 func Hello(w http.ResponseWriter, r *http.Request) {
18 w.Header().Set("Content-Type", "text/plain")
19 Fprintf(w, MESSAGE)
20 }
HTTP
package main
import (
. "fmt"
"net/http"
)
const MESSAGE = "hello world"
const ADDRESS = ":1024"
func main() {
http.HandleFunc("/hello", Hello)
if e := http.ListenAndServe(ADDRESS, nil); e != nil {
Println(e)
}
}
func Hello(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
Fprintf(w, MESSAGE)
}
27. Hello World 35
The Environment
The main shells used with modern operating systems (Linux, OSX, FreeBSD, Windows, etc.) provide a
persistent environment which can be queried by running programs, allowing a user to store configuration
values in named variables. Go supports reading and writing these variables using the os package functions
Getenv() and Setenv().
In our next example we’re going to query the environment for the variable SERVE_HTTP which we’ll
assume contains the default address on which to serve unencrypted web content.
Example 1.43
1 package main
2 import (
3 . "fmt"
4 . "net/http"
5 "os"
6 "sync"
7 )
8
9 const SECURE_ADDRESS = ":1025"
10
11 var address string
12 var servers sync.WaitGroup
13
14 func init() {
15 if address = os.Getenv("SERVE_HTTP"); address == "" {
16 address = ":1024"
17 }
18 }
19
20 func main() {
21 message := "hello world"
22 HandleFunc("/hello", func(w ResponseWriter, r *Request) {
23 w.Header().Set("Content-Type", "text/plain")
24 Fprintf(w, message)
25 })
26
27 Launch(func() {
28 ListenAndServe(address, nil)
29 })
30
31 Launch(func() {
32 ListenAndServeTLS(SECURE_ADDRESS, "cert.pem", "key.pem", nil)
33 })
34 servers.Wait()
35 }
36
THE ENVIRONMENT
package main
import (
. "fmt"
. "net/http"
"os"
"sync"
)
const SECURE_ADDRESS = ":1025"
var address string
var servers sync.WaitGroup
func init() {
if address = os.Getenv("SERVE_HTTP"); address == "" {
address = ":1024"
}
}
func main() {
message := "hello world"
HandleFunc("/hello", func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Type", "text/plain")
Fprintf(w, message)
})
Launch(func() {
ListenAndServe(address, nil)
})
Launch(func() {
ListenAndServeTLS(SECURE_ADDRESS, "cert.pem", "key.pem", nil)
})
servers.Wait()
}
func Launch(f func()) {
servers.Add(1)
go func() {
defer servers.Done()
f()
}()
}
28. Hello World 49
UDP
Both TCP/IP and HTTP communications are connection-oriented and this involves a reasonable amount
of handshaking and error-correction to assemble data packets in the correct order. For most applications
this is exactly how we want to organise our network communications but sometimes the size of our
messages is sufficiently small that we can fit them into individual packets, and when this is the case the
UDP protocol is an ideal candidate.
As with our previous examples we still need both server and client applications.
Example 1.53 UDP server
1 package main
2
3 import (
4 . "fmt"
5 "net"
6 )
7
8 var HELLO_WORLD = ([]byte)("Hello Worldn")
9
10 func main() {
11 if address, e := net.ResolveUDPAddr("udp", ":1024"); e == nil {
12 if server, e := net.ListenUDP("udp", address); e == nil {
13 for buffer := MakeBuffer(); ; buffer = MakeBuffer() {
14 if n, client, e := server.ReadFromUDP(buffer); e == nil {
15 go func(c *net.UDPAddr, packet []byte) {
16 if n, e := server.WriteToUDP(HELLO_WORLD, c); e == nil {
17 Printf("%v bytes written to: %vn", n, c)
18 }
19 }(client, buffer[:n])
20 }
21 }
22 }
23 }
24 }
25
26 func MakeBuffer() (r []byte) {
27 return make([]byte, 1024)
28 }
We have a somewhat more complex code pattern here than with TCP/IP to take account of the difference
in underlying semantics: UDP is an unreliable transport dealing in individual packets (datagrams) which
are independent of each other, therefore a server doesn’t maintain streams to any of its clients and these are
responsible for any error-correction or packet ordering which may be necessary to coordinate successive
signals. Because of these differences from TCP/IP we end up with the following generic workflow
• net.ResolveUDPAddr() to resolve the address
• net.ListenUDP() opens a UDP port and listens for traffic
UDP
package main
import (
. "fmt"
"net"
)
var HELLO_WORLD = ([]byte)("Hello Worldn")
func main() {
if address, e := net.ResolveUDPAddr("udp", ":1024"); e == nil {
if server, e := net.ListenUDP("udp", address); e == nil {
for buffer := MakeBuffer(); ; buffer = MakeBuffer() {
if n, client, e := server.ReadFromUDP(buffer); e == nil {
go func(c *net.UDPAddr, packet []byte) {
if n, e := server.WriteToUDP(HELLO_WORLD, c); e == nil {
Printf("%v bytes written to: %vn", n, c)
}
}(client, buffer[:n])
}
}
}
}
}
func MakeBuffer() (r []byte) {
return make([]byte, 1024)
}
29. UDP SERVER & CLIENT
package main
import (
. "fmt"
"net"
)
var HELLO_WORLD = ([]byte)("Hello Worldn")
func main() {
if address, e := net.ResolveUDPAddr("udp", ":1024"); e == nil {
if server, e := net.ListenUDP("udp", address); e == nil {
for buffer := MakeBuffer(); ; buffer = MakeBuffer() {
if n, client, e := server.ReadFromUDP(buffer); e == nil {
go func(c *net.UDPAddr, packet []byte) {
if n, e := server.WriteToUDP(HELLO_WORLD, c); e == nil {
Printf("%v bytes written to: %vn", n, c)
}
}(client, buffer[:n])
}
}
}
}
}
func MakeBuffer() (r []byte) {
return make([]byte, 1024)
}
package main
import (
"bufio"
. "fmt"
"net"
)
var CRLF = ([]byte)("n")
func main() {
if address, e := net.ResolveUDPAddr("udp", ":1024"); e == nil {
if server, e := net.DialUDP("udp", nil, address); e == nil {
defer server.Close()
for i := 0; i < 3; i++ {
if _, e = server.Write(CRLF); e == nil {
if text, e := bufio.NewReader(server).ReadString('n'); e == nil {
Printf("%v: %v", i, text)
}
}
}
}
}
}