go udp client/server example

7,043 views
Skip to first unread message

toxicnaan

unread,
Nov 22, 2010, 7:59:04 PM11/22/10
to golang-nuts
Hey,

my go adventures are going well, I've managed to write a simple tcp
server. However udp is going to require a bit more thinking? Can any
point me to an example go code that uses udp?

What's the best way of handling udp connections go? I'm not really
looking for stella performance, just a clean way of implementing a udp
server and have the ability to reply!

Cheers!
Lee

Andrew Gerrand

unread,
Nov 22, 2010, 8:42:19 PM11/22/10
to toxicnaan, golang-nuts

The UDPConn type shares the same interface (Conn) as TCPConn, with
which you are already familiar.

http://golang.org/pkg/net/#UDPConn

You should be able to program a UDP the same way you do TCP, using the
Read and Write methods.

To specifically read and write UDP packets, use the ReadFromUDP and
WriteToUDP methods.

Andrew

lee hughes

unread,
Nov 23, 2010, 9:35:37 AM11/23/10
to Andrew Gerrand, golan...@googlegroups.com
netlisten, err := net.Listen("udp", "127.0.0.1:9988");
conn, _ := netlisten.Accept();
log.Println("main(): connected", conn);

unknown network udp
panic: runtime error: invalid memory address or nil pointer dereference

however

netlisten, err := net.Listen("tcp", "127.0.0.1:9988");
conn, _ := netlisten.Accept();
log.Println("main(): connected", conn);


PANIC! :-).

do i specifically need to specify ListenUDP ? I just presumed that if i ask
net.Listen to return a connection type of my choice (udp, tcp).

Probably missing something fundamental here. May a code example
can shut me up.

ckrueger

unread,
Nov 23, 2010, 1:55:33 PM11/23/10
to golang-nuts
check this thread:
http://groups.google.com/group/golang-nuts/browse_thread/thread/98605e6791698697

On Nov 23, 6:35 am, lee hughes <toxicn...@gmail.com> wrote:
> netlisten, err := net.Listen("udp", "127.0.0.1:9988");
> conn, _ := netlisten.Accept();
> log.Println("main(): connected", conn);
>
> unknown network udp
> panic: runtime error: invalid memory address or nil pointer dereference
>
> however
>
> netlisten, err := net.Listen("tcp", "127.0.0.1:9988");
> conn, _ := netlisten.Accept();
> log.Println("main(): connected", conn);
>
> PANIC! :-).
>
> do i specifically need to specify ListenUDP ? I just presumed that if i ask
> net.Listen to return a connection type of my choice (udp, tcp).
>
> Probably missing something fundamental here. May a code example
> can shut me up.
>
> On Tue, Nov 23, 2010 at 1:42 AM, Andrew Gerrand <a...@golang.org> wrote:

murny...@gmail.com

unread,
Dec 11, 2013, 11:22:50 AM12/11/13
to golan...@googlegroups.com
can i ask for your tcp server coding please!!!
Reply all
Reply to author
Forward
0 new messages