Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send a string instead of byte through socket in Java

Tags:

java

port

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

like image 326
Ravindu Avatar asked Jul 03 '13 06:07

Ravindu


People also ask

How do you write a string to a socket?

SendStringOverSocket.javaSocket socket = new Socket("localhost", 7777); System. out. println("Connected!");

Can we convert byte to string in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.

How do you send a string in Java?

To send a string you must convert it to bytes using some encoding scheme first. UTF-8 is the de-facto standard nowadays.


2 Answers

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(); 
like image 152
Juned Ahsan Avatar answered Nov 09 '22 02:11

Juned Ahsan


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

}
like image 36
Josnidhin Avatar answered Nov 09 '22 04:11

Josnidhin