0

I'm new at sending data through sockets but I figured out how to do it now. My problem is that I can only send and receive bytes, is there a way that I can send and receive strings in stead of bytes? Or is it always bytes?

I'm sorry for my bad understanding of how sockets work but I'm trying (;

Thanks in advance!

2
  • Have you taken a look at this question? Commented May 25, 2014 at 10:42
  • You can just convert strings to bytes and vice versa though. Commented May 25, 2014 at 10:43

2 Answers 2

0

You can use DataStreams and writeUTF. On the other side you can read the Strings with readUTF.

        yourSocket = new Socket("yoursocket.ip", port);
        os = new DataOutputStream(yourSocket.getOutputStream());

        os.writeUTF("your string");

On the other side you can read it the same way with

 is = new DataInputStream(yourSocket.getInputStream());
 String yourString = is.readUTF();
Sign up to request clarification or add additional context in comments.

Comments

0

To send data over a socket, it must be a byte[].

Using the <string>.getBytes() method, you can retrieve a byte representation of the string. The resulting byte array can then be sent over the socket. On the receiving end, use the String constructor String(<byte array>) you can re-create the string. Both of these methods allow you to pass a character format as the second parameter (have a look at the JavaDoc). I'd recommend doing this as to make sure that, even on two different platforms, you recieve the same data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.