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

1
  • To send a string you must convert it to bytes using some encoding scheme first. UTF-8 is the de-facto standard nowadays. Commented Jul 3, 2013 at 6:07

8 Answers 8

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(); 
Sign up to request clarification or add additional context in comments.

6 Comments

Note that you are using default encoding here instead of an explicit one, which is dangerous
PrintWriter is almost always a bad idea IMO. The way that it swallows exceptions is horrible.
@JonSkeet Yeah i dont really like my own proposed solution. Lets see if it works for the user. Thinking about a better solution.
@JunedAhsan: Well just using OutputStreamWriter and write is as simple, allows you to specify the encoding, and avoids the exception nastiness.
@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.
|
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();
    }

}

1 Comment

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.
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).

2 Comments

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: 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.
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...

Comments

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

Comments

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.

1 Comment

note that the utf encoding is not a standard one, is a modified one.
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.

Comments

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();
    }

}

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.