简体   繁体   English

在Java中通过套接字发送字符串而不是字节

[英]Send a string instead of byte through socket in Java

How can i send a strin using getOutputStream method. 如何使用getOutputStream方法发送strin。 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 使用OutputStreamWriter类来实现您想要的

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: 如何使用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 : 这是使用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). 请注意,在这两种情况下,您都应明确指定编码,例如“UTF-8” - 这样可以避免使用平台默认编码(这几乎总是一个坏主意)。

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 ; 如果它是两端的Java,你可以使用DataInputStreamDataOutputStream ; 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

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

You may want to specify charset, such as "UTF-8" "UTF-16" ...... 你可能想指定字符集,例如"UTF-8" "UTF-16" ......

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

Or PrintStream : 或者PrintStream

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

Or DataOutputStream : 或者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 或者你可以找到更多的WriterOutputStream

The java.io package java.io

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. 注意:您需要使用接收方的DataInputStream readUTF()方法。

NOTE: you have to check for null in the "finally" caluse; 注意:您必须在“finally”caluse中检查null; otherwise you will run into NullPointerException later on. 否则你将在以后遇到NullPointerException。

I see a bunch of very valid solutions in this post. 我在这篇文章中看到了一堆非常有效的解决方案。 My favorite is using Apache Commons to do the write operation: 我最喜欢使用Apache Commons来执行写操作:

IOUtils.write(CharSequence, OutputStream, Charset) IOUtils.write(CharSequence,OutputStream,Charset)

basically doing for instance: IOUtils.write("Your String", socket.getOutputStream(), "UTF-8") and catching the appropriate exceptions. 基本上做的例如: IOUtils.write("Your String", socket.getOutputStream(), "UTF-8")并捕获相应的异常。 If you're trying to build some sort of protocol you can look into the Apache commons-net library for some hints. 如果您正在尝试构建某种协议,可以查看Apache commons-net库以获取一些提示。

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. Apache commons-io中还有许多其他有用的方法和类可以节省您的时间。

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: 就像在@ Josnidhin的回答中一样:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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