简体   繁体   中英

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

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.

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; 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".

In a similar vein, you have InputStream s and Reader s, which share the same relationship.

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.

In your code, then:

  • write the bytes into the first block after try ;
  • specify a Charset to use for your Reader and Writer ;
  • if you use buffering on the write side, don't forget to .flush() after you write (although closing the socket will flush automatically).

The rest is left as an exercise!

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