Send a string instead of byte through socket in Java

久未见 提交于 2019-12-28 13:46:31

问题


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:


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



回答2:


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

}



回答3:


Two options:

  • Wrap your OutputStream in an OutputStreamWriter, so you can then send the string
  • Convert a string to bytes using String.getBytes(encoding)

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




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



回答5:


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




回答6:


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.




回答7:


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.




回答8:


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

}


来源:https://stackoverflow.com/questions/17440795/send-a-string-instead-of-byte-through-socket-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!