15

How can i send a strin using getOutputStream method. It can only send byte as they mentioned. So far I can send a byte. but not a string value.

public void sendToPort() throws IOException {

    Socket socket = null;
    try {
        socket = new Socket("ip address", 4014);
        socket.getOutputStream().write(2); // have to insert the string
    } catch (UnknownHostException e) {
        System.err.print(e);
    } finally {
        socket.close();
    }

}

Thanks in advance

Ravindu
  • 2,408
  • 8
  • 30
  • 46
  • To send a string you must convert it to bytes using some encoding scheme first. UTF-8 is the de-facto standard nowadays. – Jim Garrison Jul 03 '13 at 06:07

8 Answers8

16

How about using PrintWriter:

OutputStream outstream = socket .getOutputStream(); 
PrintWriter out = new PrintWriter(outstream);

String toSend = "String to send";

out.print(toSend );

EDIT: Found my own answer and saw an improvement was discussed but left out. Here is a better way to write strings using OutputStreamWriter:

    // Use encoding of your choice
    Writer out = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(fileDir), "UTF8"));

    // append and flush in logical chunks
    out.append(toSend).append("\n");
    out.append("appending more before flushing").append("\n");
    out.flush(); 
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • 2
    Note that you are using default encoding here instead of an explicit one, which is dangerous – David Hofmann Jul 03 '13 at 06:09
  • 1
    PrintWriter is almost always a bad idea IMO. The way that it swallows exceptions is horrible. – Jon Skeet Jul 03 '13 at 06:12
  • @JonSkeet Yeah i dont really like my own proposed solution. Lets see if it works for the user. Thinking about a better solution. – Juned Ahsan Jul 03 '13 at 06:16
  • 2
    @JunedAhsan: Well just using `OutputStreamWriter` and `write` is as simple, allows you to specify the encoding, and avoids the exception nastiness. – Jon Skeet Jul 03 '13 at 06:19
  • @Ravindu it will work 'most of the time' depending on what type of content you send over the wire. All strings have to be converted to bytes using a particular encoding. The 'default' encoding can be different in each machine/jvm/os. So you can safely asume you will have problems someday if you don't explicitly set the encoding. – David Hofmann Jul 04 '13 at 05:23
  • You can shorten this to `new PrintWriter(socket.getOutputStream()).print("String to send");` by the way. But it isn't recommended, cause you should`close` the PrintWriter when you're done. – Aaron Esau Dec 30 '16 at 22:42
15

Use OutputStreamWriter class to achieve what you want

public void sendToPort() throws IOException {
    Socket socket = null;
    OutputStreamWriter osw;
    String str = "Hello World";
    try {
        socket = new Socket("ip address", 4014);
        osw =new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
        osw.write(str, 0, str.length());
    } catch (IOException e) {
        System.err.print(e);
    } catch (UnknownHostException e) {
        System.err.print(e);
    } finally {
        socket.close();
    }

}
Dick Lucas
  • 12,289
  • 14
  • 49
  • 76
Josnidhin
  • 12,469
  • 9
  • 42
  • 61
  • 8
    Because stackoverflow's horrible 6 character edit amount policy, I have to comment here that the 'UTF-8' should be "UTF-8". Remember, single quotes are for chars, whereas double quotes are use for Strings. – Dick Lucas Sep 29 '14 at 03:22
5

Two options:

Note that in both cases you should specify the encoding explicitly, e.g. "UTF-8" - that avoids it just using the platform default encoding (which is almost always a bad idea).

This will just send the character data itself though - if you need to send several strings, and the other end needs to know where each one starts and ends, you'll need a more complicated protocol. If it's Java on both ends, you could use DataInputStream and DataOutputStream; otherwise you may want to come up with your own protocol (assuming it isn't fixed already).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • eh,.... i'm abit confuse about this socket and its input / output stream. What about the receiving part? I mean how could we differentiate whether the data transferring is just a string / file ? @JonSkeet – gumuruh Aug 21 '14 at 09:51
  • @gumuruh: That sounds like an entirely different question. This question is *just* about sending a string - there's nothing about sending a file. It sounds like you should do some more research, and then ask a new question if you're still confused. – Jon Skeet Aug 21 '14 at 09:52
4

if you have a simple string you can do

socket.getOutputStream().write("your string".getBytes("US-ASCII")); // or UTF-8 or any other applicable encoding...
David Hofmann
  • 5,683
  • 12
  • 50
  • 78
3

You can use OutputStreamWriter like this:

OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
out.write("SomeString", 0, "SomeString".length);

You may want to specify charset, such as "UTF-8" "UTF-16"......

OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream(),
        "UTF-8");
out.write("SomeString", 0, "SomeString".length);

Or PrintStream:

PrintStream out = new PrintStream(socket.getOutputStream());
out.println("SomeString");

Or DataOutputStream:

DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeBytes("SomeString");
out.writeChars("SomeString");
out.writeUTF("SomeString");

Or you can find more Writers and OutputStreams in

The java.io package

johnchen902
  • 9,531
  • 1
  • 27
  • 69
1
public void sendToPort() throws IOException {
    DataOutputStream dataOutputStream = null;
    Socket socket = null;
    try {
        socket = new Socket("ip address", 4014);
        dataOutputStream = new DataOutputStream(socket.getOutputStream());
        dataOutputStream.writeUTF("2"); // have to insert the string
    } catch (UnknownHostException e) {
        System.err.print(e);
    } finally {
        if(socket != null) {
            socket.close();
        }
        if(dataOutputStream != null) {
            dataOutputStream.close();
        }
    }
}

NOTE: You will need to use DataInputStream readUTF() method from the receiving side.

NOTE: you have to check for null in the "finally" caluse; otherwise you will run into NullPointerException later on.

Multithreader
  • 878
  • 6
  • 14
1

I see a bunch of very valid solutions in this post. My favorite is using Apache Commons to do the write operation:

IOUtils.write(CharSequence, OutputStream, Charset)

basically doing for instance: IOUtils.write("Your String", socket.getOutputStream(), "UTF-8") and catching the appropriate exceptions. If you're trying to build some sort of protocol you can look into the Apache commons-net library for some hints.

You can never go wrong with that. And there are many other useful methods and classes in Apache commons-io that will save you time.

Ulises
  • 9,115
  • 2
  • 30
  • 27
0

Old posts, but I can see same defect in most of the posts. Before closing the socket, flush the stream. Like in @Josnidhin's answer:

public void sendToPort() throws IOException {
    Socket socket = null;
    OutputStreamWriter osw;
    String str = "Hello World";
    try {
        socket = new Socket("ip address", 4014);
        osw =new OutputStreamWriter(socket.getOutputStream(), 'UTF-8');
        osw.write(str, 0, str.length());
        osw.flush();
    } catch (IOException e) {
        System.err.print(e);
    } finally {
        socket.close();
    }

}