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

时间:2021-08-26 18:13:23

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.

如何使用getOutputStream方法发送strin。它只能像他们说的那样发送字节。到目前为止,我可以发送一个字节。但不是字符串值。

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

谢谢提前

8 个解决方案

#1


9  

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

#2


13  

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

}

#3


3  

Two options:

两个选择:

  • Wrap your OutputStream in an OutputStreamWriter, so you can then send the string
  • 将OutputStream封装到OutputStreamWriter中,这样就可以发送字符串
  • Convert a string to bytes using String.getBytes(encoding)
  • 使用string . getbytes(编码)将字符串转换为字节

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

注意,在这两种情况下,都应该显式地指定编码,例如。“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; otherwise you may want to come up with your own protocol (assuming it isn't fixed already).

这将只发送字符数据本身—如果您需要发送几个字符串,而另一端需要知道每个字符串的开始和结束位置,那么您将需要一个更复杂的协议。如果两端都是Java,则可以使用DataInputStream和DataOutputStream;否则,您可能希望提出自己的协议(假设它还没有修复)。

#4


3  

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


3  

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 Writers and OutputStreams in

或者你可以找到更多的作者和输出流

The java.io package

java。io包

#6


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.

注意:您需要从接收端使用DataInputStream readUTF()方法。

NOTE: you have to check for null in the "finally" caluse; otherwise you will run into NullPointerException later on.

注意:您必须在“finally”caluse中检查null;否则,稍后您将遇到NullPointerException。

#7


1  

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。写(CharSequence进行OutputStream、字符集)

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.

基本的做法,例如:IOUtils。编写(“您的字符串”、socket.getOutputStream()、“UTF-8”)并捕获适当的异常。如果您正在尝试构建某种协议,您可以查看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 common -io中还有许多其他有用的方法和类可以节省您的时间。

#8


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:

旧的帖子,但是我可以在大多数的帖子中看到同样的缺陷。在关闭插座之前,冲洗流。像在@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();
    }

}

#1


9  

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

#2


13  

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

}

#3


3  

Two options:

两个选择:

  • Wrap your OutputStream in an OutputStreamWriter, so you can then send the string
  • 将OutputStream封装到OutputStreamWriter中,这样就可以发送字符串
  • Convert a string to bytes using String.getBytes(encoding)
  • 使用string . getbytes(编码)将字符串转换为字节

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

注意,在这两种情况下,都应该显式地指定编码,例如。“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; otherwise you may want to come up with your own protocol (assuming it isn't fixed already).

这将只发送字符数据本身—如果您需要发送几个字符串,而另一端需要知道每个字符串的开始和结束位置,那么您将需要一个更复杂的协议。如果两端都是Java,则可以使用DataInputStream和DataOutputStream;否则,您可能希望提出自己的协议(假设它还没有修复)。

#4


3  

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


3  

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 Writers and OutputStreams in

或者你可以找到更多的作者和输出流

The java.io package

java。io包

#6


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.

注意:您需要从接收端使用DataInputStream readUTF()方法。

NOTE: you have to check for null in the "finally" caluse; otherwise you will run into NullPointerException later on.

注意:您必须在“finally”caluse中检查null;否则,稍后您将遇到NullPointerException。

#7


1  

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。写(CharSequence进行OutputStream、字符集)

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.

基本的做法,例如:IOUtils。编写(“您的字符串”、socket.getOutputStream()、“UTF-8”)并捕获适当的异常。如果您正在尝试构建某种协议,您可以查看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 common -io中还有许多其他有用的方法和类可以节省您的时间。

#8


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:

旧的帖子,但是我可以在大多数的帖子中看到同样的缺陷。在关闭插座之前,冲洗流。像在@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();
    }

}