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
SendStringOverSocket.javaSocket socket = new Socket("localhost", 7777); System. out. println("Connected!");
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.
To send a string you must convert it to bytes using some encoding scheme first. UTF-8 is the de-facto standard nowadays.
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();
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With