Here is a code
import java.io.*;
import java.net.*;
public class Whois
{
public static void main(String[] args)
throws Exception
{
// TODO Auto-generated method stub
int c;
Socket s = new Socket("whois.internic.net",43);
*InputStream in = s.getInputStream();
*OutputStream out = s.getOutputStream();
String str = (args.length == 0 ? "osborne.com" : args[0] ) + "
";
byte buf[] = str.getBytes();
*out.write(buf);
System.out.print("hey baby");
while ((c=in.read()) != -1)
{
System.out.print((char) c);
}
s.close();
}
}
I have marked the statements that I have problems understanding. I do not understand what OutputStream object out
will hold when it is assigned s.getOutputStream()
and what is the need of passing buf
to out
by out.write(buf)
.
I have learned Input and Output Streams using files but I do not understand getinputstream
and outputstreams
. I have googled it, read it here on SO as well as from many different books and from oracle documents as well. Please discuss it in detail.
I know how to read from files and how to write to them, but here I do not understand what is the need of passing buf
array which holds only a string. What I mean to ask is that when in has the input stream of the socket why can't we directly just read from it?
What exactly is a socket inputstream
and outputstream
?
I found something here on SO here is the link "https://stackoverflow.com/questions/12715321/java-networking-explain-inputstream-and-outputstream-in-socket", here an answer by DNA says
In Java, to send data via the socket, you get an OutputStream (1) from it, and write to the OutputStream (you output some data)."
This is confusing me, when outputStream is used to send data via socket what was the need of out.write(buf)? Why do we need to send "google.com" to outputStream?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…