简体   繁体   中英

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

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

}

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

Two options:

Note that in both cases you should specify the encoding explicitly, eg "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).

如果你有一个简单的字符串,你可以做

socket.getOutputStream().write("your string".getBytes("US-ASCII")); // or UTF-8 or any other applicable encoding...

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 Writer s and OutputStream s in

The java.io package

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.

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM