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.
Related
the first is my client, and second is server side.why the client can't send its second round msg to the server through socket? when you put something in the console, the server will respond through socket, and then send back the msg to client.but when i put something in the console for the second time, the msg cannot be sent to server anymore, please tell me why. thanks
package client;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
static Socket sock ;
static InputStreamReader IR;
public static void main(String[] args) throws IOException,
InterruptedException
{
Client client = new Client();
sock = new Socket("localhost", 1112);
IR = new InputStreamReader(sock.getInputStream());
client.run();
}
public void run() throws IOException, InterruptedException
{
while(true)
{
PrintStream PS = new PrintStream(sock.getOutputStream());
Scanner sc = new Scanner(System.in);
System.out.println("Enter your ageļ¼");
int age = sc.nextInt();
PS.println(age);
if(age == 0)
{
break;
}
System.out.println("here");
BufferedReader BR = new BufferedReader(IR);
String MSG = BR.readLine();
System.out.println("client: server has received "+MSG);
Thread.sleep(1000);
}
sock.close();
}
}
package server;
import java.io.*;
import java.net.*;
public class Server {
static ServerSocket serverSocket;
public static void main(String[] args) throws IOException,
InterruptedException {
Server server = new Server();
serverSocket = new ServerSocket(1112);
server.run();
}
public void run() throws IOException, InterruptedException
{
while(true)
{
//ServerSocket serverSocket = new ServerSocket(1112);
Socket socket = serverSocket.accept();
InputStreamReader IR = new
InputStreamReader(socket.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String msg = BR.readLine();
System.out.println("server: I have received "+msg);
Thread.sleep(2000);
if(msg != null)
{
PrintStream PS = new
PrintStream(socket.getOutputStream());
PS.println(msg);
}else
{
break;
}
}
serverSocket.close();
}
}
So when a client socket attempts to connect to a server socket, it gets put on a queue on the server-side. Then, the .accept() method on the server socket takes that request off the queue and "connects" the two sockets.
So, in your code,
the client requests connection,
the server accepts it,
client sends age to server,
server reads it and sends it back,
client sends another age to the server
server never does anything
The problem occurs after step 4 on the server-side. It calls the .accept() method again, but there is no client requesting connection so that .accept() just waits until it gets a socket requesting connection (it's called a blocking method).
You could fix this problem by moving the Socket socket = serverSocket.accept() out of the while(true) loop on the server
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'm making a program where a client uses a proxy to ask a server to retrieve content from an URL, so for example, the client types in "http://www.google.ca", and they get the html code from that webpage. I got it to work once, but I want to it work multiple times. I tried using loops but they never terminate, bufferedreader never seems to = null for the Proxy or Client class (the Server class works fine though). Any help would be greatly appreciated.
Here is my code
Client.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception {
Client serv = new Client();
serv.run();
}
public void run() throws Exception {
Socket sock = new Socket("localhost", 7777); //connects to Proxy
PrintStream ps = new PrintStream(sock.getOutputStream()); //output stream to Proxy
InputStreamReader ir = new InputStreamReader(sock.getInputStream()); //input stream from Proxy
BufferedReader br = new BufferedReader(ir);
Scanner scanner = new Scanner(System.in); //take input from keyboard
//user types in an URL, outputs content of URL
for(int i = 0; i < 100; i++) {
ps.println(scanner.nextLine());
String inputLine;
while((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
System.out.println("DONE");
}
sock.close();
scanner.close();
}
}
Proxy.java
import java.net.*;
import java.io.*;
public class Proxy {
public static void main (String[] args) throws Exception {
Proxy serv = new Proxy();
serv.run();
}
public void run() throws Exception {
ServerSocket ss = new ServerSocket(7777);
Socket sock = ss.accept();
//input and output streams to and from Client
InputStreamReader ir = new InputStreamReader(sock.getInputStream());
BufferedReader br = new BufferedReader(ir);
PrintStream psToClient = new PrintStream(sock.getOutputStream());
//input and output streams to and from Server
Socket sck = new Socket("localhost", 8888);
PrintStream ps = new PrintStream(sck.getOutputStream());
InputStreamReader irFromServer = new InputStreamReader(sck.getInputStream());
BufferedReader brFromServer = new BufferedReader(irFromServer);
//passes message from Client to Server, passes URL content from Server back to Client
for(int i = 0; i < 100; i++) {
String message = br.readLine();
ps.println(message);
System.out.println("Client wants me to tell Server he wants the content of: " + message);
String inputLine;
while((inputLine = brFromServer.readLine()) != null) {
psToClient.println(inputLine);
//psToClient.flush();
System.out.println(inputLine);
}
System.out.println("DONE");
}
sock.close();
ss.close();
sck.close();
}
}
Server.java
import java.net.*;
import java.io.*;
public class Server {
public static void main (String[] args) throws Exception {
Server serv = new Server();
serv.run();
}
public void run() throws Exception {
ServerSocket ss = new ServerSocket(8888);
Socket sock = ss.accept();
//input and output streams to and from Proxy
InputStreamReader ir = new InputStreamReader(sock.getInputStream());
BufferedReader br = new BufferedReader(ir);
PrintStream psToProxy = new PrintStream(sock.getOutputStream());
//retrieves content from requested URL and sends back to Proxy
for(int i = 0; i < 100; i++) {
String request = br.readLine();
System.out.println("Proxy told me Client wants the content from: " + request);
//makes URL object using String value from Client
URL url = new URL(request);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
//sends URL content back to Client, via Proxy
String inputLine;
while ((inputLine = in.readLine()) != null) {
psToProxy.println(inputLine);
//psToProxy.flush();
System.out.println(inputLine);
}
System.out.println("FINISHED SENDING CONTENT");
in.close();
}
sock.close();
ss.close();
}
}
bufferedreader never seems to = null
Your question is a little imprecise. What you mean is that BufferedReader.readLine() never returns null. That only happens when the peer closes the connection. If he never closes it, readLine() won't return null.
If you're writing an HTTP proxy you need to have a good look at RFC 2616, and specifically the requirements about the Content-length header, the Connection: close header, and chunked transfer encoding. Just reading the response stream to its end is in general not sufficient.
I am writing a client-server program in java using TCP/IP. For the purpose, I wrote the following codes:
serversock.java:
import java.net.*;
import java.io.*;
public class serversock {
public static void main(String[] args) throws IOException
{
ServerSocket sersock = null;
try
{
sersock = new ServerSocket(10007);
}
catch (IOException e)
{
System.out.println("Can't listen to port 10007");
System.exit(1);
}
Socket clientSocket = null;
System.out.println("Waiting for connection....");
try
{
clientSocket = sersock.accept();
}
catch ( IOException ie)
{
System.out.println("Accept failed..");
System.exit(1);
}
System.out.println("Conncetion is established successfully..");
System.out.println("Waiting for input from client...");
PrintWriter output = new PrintWriter(clientSocket.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = input.readLine();
while ( inputLine != null)
{
output.println(inputLine);
System.out.println("Server: " + inputLine);
inputLine = input.readLine();
}
input.close();
clientSocket.close();
sersock.close();
}
}
clientsock.java:
import java.util.*;
import java.io.*;
import java.net.*;
public class clientsock
{
public static void main(String[] args) throws IOException
{
Socket sock = new Socket("localhost",10007);
// Scanner scan = new Scanner(System.in);
PrintWriter output = new PrintWriter(sock.getOutputStream(),true);
BufferedReader input = new BufferedReader( new InputStreamReader(sock.getInputStream()));
String line = null;
BufferedReader stdInput = new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter data to send to server: ");
line = stdInput.readLine();
while ( (line) != "bye")
{
output.println(line.getBytes());
line = stdInput.readLine();
System.out.println("Server sends: " + input.read());
}
sock.close();
}
}
Now on running the programs I got the following output:
server:
shahjahan#shahjahan-AOD270:~/Documents/java$ java serversock
Waiting for connection....
Conncetion is established successfully..
Waiting for input from client...
Server: [B#4e25154f
shahjahan#shahjahan-AOD270:~/Documents/java$
client:
shahjahan#shahjahan-AOD270:~/Documents/java$ java clientsock
Enter data to send to server:
qwe
sdf
^Cshahjahan#shahjahan-AOD270:~/Documents/java$
The server is recieving different symbols, and client receives nothing. Please help me to solve it.
In the client replace:
output.println(line.getBytes());
with
output.println(line);
Guys am sick of this client and server chat program plz help me
my program is compiled and runing but the problem is that when i trying to pass the msg to the server its not working it pass by itself..now what correction i do...
Server Code:
import java.io.*;
import java.net.*;
class serv
{
ServerSocket s;
Socket c;
DataInputStream dis;
DataOutputStream dos;
BufferedReader disi;
public serv()
{
try
{
s = new ServerSocket(2000,0,InetAddress.getLocalHost());
System.out.println("Server is Created");
c = s.accept();
System.out.println("Request Accepted");
}
catch(Exception e)
{
System.out.println(e);
}
}
public void talk()throws IOException,UnknownHostException
{
dis = new DataInputStream(c.getInputStream());
dos = new DataOutputStream(c.getOutputStream());
disi = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str = new String(disi.readLine());
dos.writeUTF(str);
System.out.println(str);
}
}
public static void main(String args[])
{
try
{
serv c = new serv();
c.talk();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Client Code:
import java.io.*;
import java.net.*;
class clien
{
Socket c;
DataInputStream dis;
BufferedReader disi;
DataOutputStream dos;
public clien()throws IOException,UnknownHostException
{
c=new Socket(InetAddress.getLocalHost(),2000);
System.out.println("Request is sended");
}
public void talk()throws IOException,UnknownHostException
{
try
{
dis=new DataInputStream(c.getInputStream());
dos=new DataOutputStream(c.getOutputStream());
disi=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String str=new String(disi.readLine());
dos.writeUTF(str);
System.out.println(str);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
try
{
clien c=new clien();
c.talk();
}
catch(Exception e){ }
}
}
There are tons of problems.
It seems as if you're trying to do some kind of protocol like this:
Client connects to server
Client sends message to server
Server receives message
A peer-to-peer type system. Not sure if you're expecting the server to be seen as another client (you type messages into it to send it to the client), but the problem is that right when the connection establishes, both Client and Server go into a loop. In this loop, there's only 1 thing you can focus on.
Client:
main(String[]) -> connect -> read input from user (loop)
start program -> connect -> start listening for info from server
Server:
main(String[]) -> accept connection -> read input from user (loop)
If you want your client to receive info from the server and be able to send info aswell, you need 2 threads.
static Socket s;
static DataOutputStream out;
static DataInputStream in;
public static void main(String[] args) {
try {
s = new Socket("host", 2000);
out = new DataOutputStream(s.getOutputStream());
in = new DataInputStream(s.getInputStream());
new Thread(new Runnable() {
public void run() {
Scanner scanner = new Scanner(System.in);
String input;
while(!(input = scanner.nextLine()).equals("EXITPROGRAM")) {
out.writeUTF(input); //sends to client
}
}
}).start();
while(true) {
String infoFromServer = in.readUTF();
//you can print to console if you want
}
}catch(Exception e) { }
}
Now, this will allow the client to receive input from the user (from the console) AND receive data from the server aswell. You can use the same structure for your server aswell if that's what you're going for.