Difference between printwritter and BufferedReader for Java server sockets - java

Wanted to know with java sockets whats the difference between the two. Trying to understand how to make a java server socket code using lessons from oracle and this is what it shows at the momment on their tutorials
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {

-Reader and -Writers are character-based and streams are byte-based.
In your example. You use writer when you want to write something to the socket and reader when you read something from the socket.
Hank

Related

Trouble with sending / receiving data

So I am attempting to send data to myself and receive the data then print it, now I have been testing for a while and I have noticed its not sending anything, in fact, maybe it is and I am not receiving it properly, I need assistance with this please.
This is what I am using to send data
String host = "127.0.0.1";
int port = Options.port;
Socket socket = new Socket(host, port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(msg + "\n");
bw.flush();
This is what I am using to receive, I always use this method and it never works so I would not be surprised if this was the root cause.
ServerSocket serverSocket = new ServerSocket(Options.port);
System.out.println("[Listening on port] " + Options.port);
while(true){
Socket socket = serverSocket.accept();
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println(message);
}
1) replace:
Socket socket = serverSocket.accept();
socket = serverSocket.accept();
with:
Socket socket = serverSocket.accept();
2) If this does not solve the problem, set ports as int values, without Options.port

Socket reading strategy in java

I have a project where I will receive data from a TCP port, I need to be constantly waiting to check if I receive data.
My code for now is:
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ip,8000));
while(true){
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
InputStream inFromClient = socket.getInputStream();
while(true){
int i = inFromClient.read();
System.out.println("data = " + i);
l++;
}
I don't like this strategy based in while(true), There is some strategy to receive data from a callback or something similar?
You can use java File I/O (Featuring NIO.2). Please follow the link for sample
https://github.com/dublintech/async_nio2_java7_examples/blob/master/echo-nio2-server/src/main/java/com/alex/asyncexamples/server/AsyncEchoServer.java

Java socket programming writebytes to readline

I am trying to get a java server and client communicating. For streaming data to the server I have this code:
Socket ClientSocket = null;
ClientSocket = new Socket(IPAddress, portInt);
DataOutputStream outToClient = new DataOutputStream(ClientSocket.getOutputStream());
outToClient.writeBytes(command);
outToClient.flush();
And for the server I have:
ServerSocket mysocket = new ServerSocket(8081);
Socket connectionsocket = mysocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionsocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionsocket.getOutputStream());
//program hangs here, client not sending
GetRequest = inFromClient.readLine();
System.out.println("Received: " + GetRequest);
These are only short portions of the overall code, I have found that the program hangs on the server side when the readLine(); is reached. I am trying to send data with writeBytes(command); where command is a string. Any suggestions? thanks.
writebytes to readline
Stop right there. If you're using readLine() you're using BufferedReader, which is a Reader, which means you should be using a Writer to talk to it, which means you should be using a BufferedWriter, and as you're reading lines you must write lines, which means writing a line terminator (which you aren't presently doing), which means you should use BufferedWriter.newline().
Or PrintWriter.println(), but don't forget to check for errors, as it swallows exceptions.
Don't directly use readLine
Instead try this
If( inFromClient.ready()){
// read string here.
}
It might be possible that buffer is not ready and you are trying to read. So it can create problem.

Debug socket communication in eclipse

I need to know the flow of the below given program:
Client Class:
1. Socket sock = new Socket("localhost", 1101);
2. PrintWriter write = new PrintWriter(sock.getOutputStream());
3. write.println("Hello");
4. write.close();
Server Class:
1. ServerSocket sersock = new ServerSocket(1101);
2. sock = sersock.accept();
3. InputStreamReader read = new InputStreamReader(sock.getInputStream());
4. BufferedReader buf = new BufferedReader(read);
5. System.out.println(buf.readLine());
6. buf.close();
When I run the server class and then the client class, how does the flow of the program work?
It flows exactly how it reads.
Server binds the socket to port 1101, listens for connections
1. ServerSocket sersock = new ServerSocket(1101);
2. sock = sersock.accept();
Client connects to server and sends "hello" and closes connection.
1. Socket sock = new Socket("localhost", 1101);
2. PrintWriter write = new PrintWriter(sock.getOutputStream());
3. write.println("Hello");
4. write.close();
Server reads and prints line from input stream after a connection has been made then closes the reader.
3. InputStreamReader read = new InputStreamReader(sock.getInputStream());
4. BufferedReader buf = new BufferedReader(read);
5. System.out.println(buf.readLine());
6. buf.close();

Should I have two threads for input/output or use NIO?

I have been working on a (relatively) simple tcp client/server chat program for my networking class. The problem that I am running into is I am using blocking calls, such as read() and writeBytes(). So, whenever I try to send a message to my server, the server does not print it out until it writes one back. For this situation, would using one thread for input and one thread for output be the most sensible solution, or would using NIO serve me better? Just to give you an idea of what my code looks like now, my server is:
ServerSocket welcomeSocket = new ServerSocket(port);
DataOutputStream output;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(
System.in));
String sentence;
while ((sentence = inFromUser.readLine()) != null) {
Socket connectionSocket = welcomeSocket.accept();
output = new DataOutputStream( connectionSocket.getOutputStream());
output.writeBytes(sentence + "\n");
BufferedReader inFromServer = new BufferedReader( new InputStreamReader(
connectionSocket.getInputStream()));
System.out.println("Client said: " + inFromServer.readLine());
connectionSocket.close();
}
The client code is essentially the same. Thanks for your time!
Just use two threads unless you want to learn about NIO. The Java tutorial has examples of spawning threads to handle client connections to a ServerSocket. Look toward the bottom of "Writing the Server Side of a Socket".

Categories