My S/W simulation of GoBack N protocol gives warning- [deprecation] readLine() in DataInputStream has been deprecated (while reading from streams) while running both client & server programs .Please tell me a solution.Is there any alternative for readLine()? Here is my client/server programs
//Server Program
import java.io.*;
import java.net.*;
import java.lang.*;
public class gobacksender
{
public static void main(String[] args)throws Exception
{
//Establishing connection
ServerSocket ss=new ServerSocket(4444);
System.out.println("Waiting for connection........");
Socket s=ss.accept();
System.out.println("Connected to client at:"+s);
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
int sptr=0,sws=8,i,ano,nf,n;
String sbuf[]=new String[8];
String ch,ch1;
System.out.println("Enter the no.of frames");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter the "+nf+" messages to be send");
for(i=1;i<=nf;i++)
{
sbuf[sptr]=in.readLine();
p.println(sbuf[sptr]);
sptr=++sptr%8;
}
sws-=nf;
do
{
ano=Integer.parseInt(in.readLine());
System.out.println("Received acknowledgement for:"+ano);
System.out.println("Retransmitting...............");
for(i=ano-1;i<nf;i++)
p.println(i);
ch1=in1.readLine();
}while(ch1.equals("yes"));
sws+=nf;
}
else
{
System.out.println("the no.of frames exceed window size");
}
ano=Integer.parseInt(in1.readLine());
System.out.println("Acknowledgement received for"+ano+"frames");
s.close();
}
}
//Client Program
import java.io.*;
import java.net.*;
import java.lang.*;
public class gobackreceiver
{
public static void main(String[] args)throws Exception
{
//Connection establishment
Socket s=new Socket("localhost",4444);
System.out.println("Connected to server at:"+s);
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
String rbuf[]=new String[8];
int i,rptr=0,rws=8,nf,n;
String ch,ch1;
do
{
nf=Integer.parseInt(in1.readLine());
System.out.println("No.of messages",nf);
if(nf<rws)
{
for(i=1;i<=nf;i++)
{
rbuf[rptr]=in1.readLine();
rptr=++rptr%8;
System.out.println("The received frame"+(rptr+1)+"is:"+rbuf[rptr]);
}
rws-=nf;
do
{
System.out.println("Enter the nak number");
n=Integer.parseInt(in.readLine());
if((1<=n)&&(n<=nf))
{
p.println(n);
for(i=n;i<nf;i++)
{
rbuf[i]=in1.readLine();
System.out.println("the received frame"+i+"is;"+rbuf[i]);
}
}
else
{
System.out.println("Invalid nak");
}
System.out.println("Anymore frames lost?");
ch1=in.readLine();
p.println(ch1);
}while(ch1.equals("yes"));
System.out.println("Ack sent");
p.println(rptr+1);
rws+=nf;
}
else
break;
ch=in.readLine();
}while(ch.equals("yes"));
s.close();
}
}
Copied from the Java API Docs:
Deprecated.
This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
DataInputStream d = new DataInputStream(in);
with:
BufferedReader d
= new BufferedReader(new InputStreamReader(in));
If you get such warnings, your first look should always be on the API or at least googling..
Related
This is the code for my server, its supposed to take an input from the user, print it into console, then send it back to the user.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class DateServer {
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(10219);
Socket s = listener.accept();
InputStreamReader in = new InputStreamReader(s.getInputStream());
BufferedReader input = new BufferedReader(in);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println("connected");
out.flush();
System.out.println("connected");
String test;
while (true) {
try {
test = input.readLine();
System.out.println(test);
out.println(test + " is what I recieved");
out.flush();
} catch(Exception X) {System.out.println(X);}
}
}
}
This is the code for the client:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;
public class DateClient {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws Exception {
System.out.println("Enter IP Address of a machine that is");
System.out.println("running the date service on port 10219:");
String serverAddress = keyboard.next();
Socket s = new Socket(serverAddress, 10219);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
System.out.println(input.readLine());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
} catch(Exception X){System.out.println(X);}
}
}
}
This was designed to work across a LAN network. I have no idea why it doesn't work, all that happens is the client will get the message "connected" and nothing else will happen, no matter what is typed into the client end. I'm a noob when it comes to java, but after a bunch of googling and searching through the java libraries, I can't seem to make it work. What did I do wrong?
You send one line from the server to the client, but in your client you wait for two lines before accepting user input to be sent to the server.
Bearing in mind that input.readLine() will block until data is received, can you spot the deadlock here:
Server:
out.println("connected");
while (true) {
try {
input.readLine();
}
}
Client:
input.readLine();
while(true) {
try {
input.readLine();
out.println(keyboard.next());
}
}
(extraneous code trimmed away to show just the problematic sequence of statements)
Both your client and server mutually wait for each other trying to do input.readLine().
This can be easily seen if you remove server's out.println("connected") and its corresponding client's first input.readLine().
On the client, you should probably write first and only then read the response. Try reordering the following lines:
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
to get
out.println(keyboard.next());
out.flush();
System.out.println(input.readLine());
In the client, try changing
PrintWriter out = new PrintWriter(s.getOutputStream());
System.out.println(input.readLine());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.next());
out.flush();
} catch(Exception X){System.out.println(X);}
}
to
PrintWriter out = new PrintWriter(s.getOutputStream());
while(true){
try{
System.out.println(input.readLine());
out.println(keyboard.nextLine());
out.flush();
} catch(Exception X){System.out.println(X);}
}
Your client is trying to read two lines, but your server sends just one, then polls for input, so both are locked. Also, sinc your server is reading line-by-line, your client should be sending data line-by-line.
I am trying to set up a server with a client and a handler. The client should ask for a string from the user. This should then be written to an OutputStream, get read in by the handler which then saves the string to its own OutputStream before passing it back to the client. I know that this program is completely pointless, I am just trying to get my head around how servers, clients and handlers work.
Here is my code so far:
Server
public class Server {
public static void main (String args[]) throws IOException {
int port = 8080;
ServerSocket server = new ServerSocket(port);
while (true) {
System.out.println("Waiting for client...");
Socket client = server.accept();
System.out.println("Client from "+client.getInetAddress()+" connected.");
Handler handler = new Handler(client);
handler.run();
}
}
}
Handler
class Handler extends Thread {
private Socket client;
public Handler(Socket c) {
client = c;
}
public void run() {
try {
Thread.sleep(3000);
System.out.println("1");
PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(client.getInputStream(),
"UTF-8"));
System.out.println("2");
String message = in.readLine();
System.out.println("4");
System.out.println("5");
out.println(message);
out.flush();
client.close();
System.out.println("Finish");
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Client
public class Client {
public static void main (String args[]) throws IOException {
Socket server = new Socket("127.0.0.1", 8080);
System.out.println("Attempting connection...");
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a string:");
String message = scan.next();
PrintWriter out = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(server.getInputStream(),
"UTF-8"));
out.println(message);
String messageReturn = in.read();
scan.close();
System.out.println("Server said: " + messageReturn);
in.close();
out.close();
}
}
The problem is that the handler seems to hang when it tries to read the message in. This problem seems similar to the one presented here: Socket problem - readline won't work properly
But this solution isn't working for me. I have tried using objectInputStreams instead of my current solution, but this didn't work either.
I doubt whether your client code will compile. The return type for this is int.
String messageReturn = in.read();
Anyway, this should work:
package network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main (String args[]) throws IOException {
Socket server = new Socket("127.0.0.1", 9890);
System.out.println("Attempting connection...");
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a string:");
String message = scan.next();
PrintWriter out = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
out.println(message);
// NOTE this
String messageReturn = in.readLine();
scan.close();
System.out.println("Server said: " + messageReturn);
in.close();
out.close();
}
}
Note Port has been changed.
Server Output
Waiting for client...
Client from /127.0.0.1 connected.
1
Client Output
Attempting connection...
Please enter a string:
Hello
The problem might be that you do not send an escape sequence with your response. ReadLine() waits till it gets an escape. Try sending a "\n" with your response. There is an article about problems using readLine() and println() with sockets. It also shows how to solve it.
ReadLine() / Println() and sockets
I've been trying to write a client process that will communicate with a serve.
I used the same code below but instead of scanner i used BufferedReader and the client input was a string. Furthermore, the server just changes the string to uppercase and sends it back to the client to be displayed on the screen. It worked.
However, when i changed the code so that the client can enter a double number [(ex: 1.6) the server should round it and send it back so that it'll be printed on the screen], i get no response.
And i got this error:
run:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at socketserver.SocketServer.main(SocketServer.java:38)
Java Result: 1
notes:
I am using NetBeans.
I used Scanner instead of using BufferedReader so that i'll be able to read a double number.
Client class
package socketclient;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class SocketClient {
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws Exception
{
double inputDouble;
double modifiedNum;
Scanner inFromUser = new Scanner(System.in);
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
Scanner inFromServer = new Scanner(clientSocket.getInputStream());
inputDouble = inFromUser.nextDouble();
outToServer.writeDouble(inputDouble);
modifiedNum = inFromServer.nextDouble();
System.out.println("FROM SERVER: " + modifiedNum);
outToServer.close();
clientSocket.close();
}
}
Server class
package socketserver;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class SocketServer {
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws Exception
{
double clientNum;
double roundedNum;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
Scanner inFromClient = new Scanner(connectionSocket.getInputStream());
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientNum = inFromClient.nextDouble();
roundedNum= Math.round(clientNum);
outToClient.writeDouble(roundedNum);
}
}
}
Your error is to use Scanner to read data sent by client from the server and the converse.
You use DataOutputStream to sent a double so you need a DataInputStream to read the double; on both sides.
Change your Scanners to DataInputStream for inputFromServer and inputFromClient. Also don't forget to flush your outputs and close the streams at the end.
so I am having an issue with reading input from a client. It works completely fine whenever I am using my if statements without the while statements wrapped around it in the server class. Could anybody point me to why this may be failing?
Server class:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception
{
Server myServer = new Server();
myServer.run();
}
public void run() throws Exception
{
//Initializes the port the serverSocket will be on
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("The Server is waiting for a client on port 9999");
//Accepts the connection for the client socket
Socket socket = serverSocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
//Confirms that the message was received
System.out.println(message);
//When this while is here. The match fails and it goes to the else statement.
//Without the while statement it will work and print "Received our hello message."
//when the client says HELLO.
while(message != null)
{
if(message.equals("HELLO"))
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Received our hello message.");
}
else
{
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("Did not receive your hello message");
}
}
}
}
Client class:
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception
{
Client myClient = new Client();
myClient.run();
}
public void run() throws Exception
{
Socket clientSocket = new Socket("localhost", 9999);
//Sends message to the server
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
Scanner scan = new Scanner(System.in);
String cMessage = scan.nextLine();
ps.println(cMessage);
//Reads and displays response from server
InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message = br.readLine();
System.out.println(message);
}
}
You're never modifying message inside the while loop so you have an infinite loop.
Try
while((message = br.readLine()) != null)
You only loops at the Server side, while u forgot to loop at the Client side, I did a quick fix for you, and also help you closed your connections.
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception
{
Server myServer = new Server();
myServer.run();
}
public void run() throws Exception
{
//Initializes the port the serverSocket will be on
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("The Server is waiting for a client on port 9999");
//Accepts the connection for the client socket
Socket socket = serverSocket.accept();
InputStreamReader ir = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(ir);
String message;
//= br.readLine();
//Confirms that the message was received
//When this while is here. The match fails and it goes to the else statement.
//Without the while statement it will work and print "Received our hello message."
//when the client says HELLO.
PrintStream ps = new PrintStream(socket.getOutputStream());
while((message =br.readLine())!=null)
{
System.out.println(message);
if(message.equals("HELLO"))
{
ps.println("Received our hello message.");
}
if(message.equals("END"))
{
ps.println("Client ended the connection");
break;
}
else
{
ps.println("Did not receive your hello message");
}
}
ps.close();
br.close();
ir.close();
serverSocket.close();
}
}
Client.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception
{
Client myClient = new Client();
myClient.run();
}
public void run() throws Exception
{
Socket clientSocket = new Socket("localhost", 9999);
//Sends message to the server
PrintStream ps = new PrintStream(clientSocket.getOutputStream());
Scanner scan = new Scanner(System.in);
String cMessage ="";
InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
BufferedReader br = new BufferedReader(ir);
while(!(cMessage.trim().equals("END"))){
cMessage = scan.nextLine();
ps.println(cMessage);
//Reads and displays response from server
String message = br.readLine().trim();
System.out.println(message);
}
br.close();
ir.close();
scan.close();
ps.close();
clientSocket.close();
}
}
Your code is working just fine for sending one 'HELLO' message.
However, like ^Tyler pointed out, If you want to keep sending messages you need to move 'while((message = br.readLine()) != null)' in the while loop.
Using a loop like you are...
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
sleep(in);
if(!in.ready()){
break;
}
}
There is a cheater way that I figured out.
private static void sleep(BufferedReader in) throws IOException {
long time = System.currentTimeMillis();
while(System.currentTimeMillis()-time < 1000){
if(in.ready()){
break;
}
}
}
This might be sloppy, but if you make a sleep method that waits an amount of time and just keep checking if the BufferedReader is "ready." If it is, you can break out, but then when you come out check again. -- Maybe you could just return a boolean instead of checking twice, but the concept is there.
trying to make a simple client server chat program. I've already go it so that the server reads a user input which is then sent to the client. the client then receives this and displays it. I then have the client reading the user input and sending it to the server however the server doesn't receive it. Heres my code:
Client:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
class client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Waiting for server to respond... \n");
while (!in.ready()) {}
System.out.print("Received Message: ");
System.out.println(in.readLine()); // Read one line and output it
System.out.print("\n");
//in.close();
System.out.print("Message:");
Scanner sc = new Scanner (System.in);
String data2 = sc.nextLine();
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending Message: '" + data2 + "'\n");
out.print(data2);
out.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Server:
import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
class server {
public static void main(String args[]) {
try {
System.out.println("Waiting for client connection...");
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.println("Client has connected!\n");
System.out.print("Message:");
Scanner sc = new Scanner (System.in);
String data = sc.nextLine();
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending Message: '" + data + "'\n");
out.print(data);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
while (!in.ready()) {out.close();}
System.out.print("Received Message: ");
System.out.println(in.readLine()); // Read one line and output it
System.out.print("\n");
//in.close();
//in.close();
//out.close();
//skt.close();
//srvr.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Both the client and the server use the same code for send/receive so I don't understand why the server won't receive.
Cheers,
Tom
print() send the text but not a new line. Try println() instead.
readLine() on the server waits for a new line, which you are not sending.
BTW: I wouldn't test for in.ready() this is more likely to be confusing than useful IMHO.