0

I have a few lines in Java

out.write(223);
out.writeBytes("something");
out.writeInt(434);

So far I did not seem to find what is the alternative of Java DataOutputStream in Go and did not find similar functions to .write .writebytes. writeint. I'd really appreciate some help :) Also, it would be great if you could show me the full code on how to connect to specific IP and port and output bytes, integers and other data to that IP, like with DataOutputStream.

kostix
  • 51,517
  • 14
  • 93
  • 176
OpenSource
  • 15
  • 4
  • Please note that [the language is called Go](https://golang.org/doc/faq#go_or_golang). Also note that you should not include the name of the language to the question's title. – kostix Jul 03 '20 at 14:30

1 Answers1

1

Go, luckily, has a more fine-grained approach.

You have the encoding/binary package in the Go's stdlib, which is able to format integer data types as binaries — both in little-endian (as that DataOutputStream appears to do) and big-endian.
Start with encoding/binary.LittleEndian.PutUint* methods. They place encoded bytes into a slice, which you can then write the usual way (see below).

Everything in Go, which is able to "ingest bytes" implements the special interface, io.Writer; files and TCP sockets to this as well.

So you write what you call "bytes" — opaque lumps of bytes are usually operated using so-called byte slices, []byte, in Go — directly to any object which implemets io.Writer. To write an integer value, you first encode it to a byte slice and then write the same way.

Strings are a more interesting topic. I see no mention in the docs on DataOutputStream about how it deals with character encoding, so I have no idea what to suggest.
Still, you can write any Go string to an io.Writer by calling io.WriteSting helper function.


Regarding your

… it would be great if you could show me the full code on how to …

please, read this.

To get started, please do this:

  1. Complete the Tour.
  2. Read "Effective Go".

This will have you covered with, like, 90%, of the necessary knowledge.
The rest can be obtained by reading the Go Blog; in particular, these articles:

kostix
  • 51,517
  • 14
  • 93
  • 176