Ravindu
Ravindu

Reputation: 2550

Send a string instead of byte through socket in Java

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

Upvotes: 15

Views: 78288

Answers (8)

Ulises
Ulises

Reputation: 9645

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.

Upvotes: 1

Juned Ahsan
Juned Ahsan

Reputation: 68715

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

Upvotes: 16

Josnidhin
Josnidhin

Reputation: 12504

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

}

Upvotes: 15

parvuselephantus
parvuselephantus

Reputation: 181

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

}

Upvotes: 0

johnchen902
johnchen902

Reputation: 9609

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

Upvotes: 3

Multithreader
Multithreader

Reputation: 878

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.

Upvotes: 1

David Hofmann
David Hofmann

Reputation: 5775

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503509

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

Upvotes: 5

Related Questions