简体   繁体   English

用Java写入python套接字服务器

[英]Write to a python socket server in java

I want to write a string to a socket server in java in bytes, then receive the answer (a known length of bytes). 我想以字节为单位将字符串写入java中的套接字服务器,然后接收答案(字节的已知长度)。

I have looked around and there are many tutorials, but I can't seem to find a specific function to handle the bytes, also, I don't seem to be able to perform functions on out. 我环顾四周,有很多教程,但是我似乎找不到特定的函数来处理字节,而且,我似乎也无法执行这些功能。 This stays red underlined. 这保持红色下划线。

import java.io.*;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;


public class SocketTest {

    public static void main(String [] args) throws IOException {


        String hostName = "localhost";
        int portNumber = 10000;

        try (

                //open a socket
                Socket clientSocket = new Socket(hostName, portNumber);


                BufferedReader in =  new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out =  new PrintWriter(clientSocket.getOutputStream(), true);


        ) {

            System.out.print("Something went wrong");

        }

}


    try {

        out.XXX;   //can't seem to execute any function on this. 
    } catch (Exception e) {
        e.printStackTrace();
    }

First things first: you are misusing the try-with-resources statement. 首先,要注意的是:您正在滥用try-with-resources语句。

The syntax is: 语法为:

try (
    // declare and open resources here
) {
    // use these resources here
}
// resources are closed here, before you even try to...
catch (SomeException e) {
    // catch exceptions
}

Then, in Java, you have OutputStream s and Writer s; 然后,在Java中,您具有OutputStreamWriter the first write bytes, the second write characters; 第一个写入字节,第二个写入字符; if a Writer wraps an OutputStream , then you need to specify the charset, from which an encoder will be created which will convert your chars into bytes before sending it "along the wire". 如果Writer包装了OutputStream ,则需要指定字符集,从该字符集将创建一个编码器,该编码器会将您的字符转换为字节,然后再“沿线”发送。

In a similar vein, you have InputStream s and Reader s, which share the same relationship. 同样,您有InputStreamReader ,它们共享相同的关系。

In general, if you do not specify a charset to use for Reader s or Writer s, the default is used -- and this may, or may not, be UTF-8. 通常,如果未指定要用于ReaderWriter的字符集,则使用默认字符集-可以(也可以不)为UTF-8。

In your code, then: 然后在您的代码中:

  • write the bytes into the first block after try ; try后将字节写入第一个块;
  • specify a Charset to use for your Reader and Writer ; 指定一个用于你的ReaderWriterCharset ;
  • if you use buffering on the write side, don't forget to .flush() after you write (although closing the socket will flush automatically). 如果在写侧使用缓冲,请不要在写后忘记使用.flush() (尽管关闭套接字会自动刷新)。

The rest is left as an exercise! 剩下的作为练习!

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

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