I'm practising WebSocket in java and wrote two simple programs which one of them is a server that starts listening in port 9090 and receives a string as input from the client then makes a string uppercase and returns back to the client.
The program has no error but for some reason, it does not work. I can't find out what is the problem.
After debuting it seems like the server doesn't receive the inputs string even though both sides connect to each other successfully. When the user inputs his/her string the client sends it to the server but the server doesn't receive it, therefore, both programs go to the wanting stage and the application will not respond.
could you please help me with the issue?
Thanks in advance
server-side code :
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
// Start listening at port 9090
ServerSocket s = new ServerSocket(9090);
System.out.println("Started: " + s);
Socket socket = s.accept();
System.out.println("conecction accepted by " + socket);
try {
// Buffer reader to get input and save it as "in"
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()
)
);
// write the output as "out"
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()
)
));
// A Loop for waiting to receive the input from the client
while (true) {
System.out.println("Watting for inpute line ...");
String line = in.readLine();
// print the input string to console to make sure it recive the input
System.out.println("inputed Line: " + line);
// sent back upper case string to client
out.println(line.toUpperCase());
out.flush();
}
}finally {
System.out.println("closing...");
socket.close();
}
}
}
The cline side code:
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
// get the Address for localhost
InetAddress addr = InetAddress.getByName(null);
//Connect to the server on pprt 9090
Socket s = new Socket(addr,9090);
// read and write to server using buffer reader and printwriter
try{
BufferedReader in = new BufferedReader(
new InputStreamReader(
s.getInputStream()
)
);
PrintWriter out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(s.getOutputStream())
)
);
//Get the Ipute string from user
Scanner input = new Scanner(System.in);
while (true){
System.out.println("Enter your text:");
String line = input.nextLine();
if(line.equals("quit"))
break;
// Sent the input string to the server using 'out'
out.println(line);
// Recive the upper case string from server
String response = in.readLine();
System.out.println("Echo:... " + response);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
System.out.println("closing...");
s.close();
}
}
}
The server side is waiting to read a line from the client, it should work if you flush the PrintWriter on the client side:
// Sent the input string to the server using 'out'
out.println(line);
out.flush();
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 recently programmed a simple Java server, and a client to test the server. The server is supposed to receive messages from the client, and send a random substring of the message back. The problem is this: When I send the message using the client program, the server does not respond. Then, when I kill the client program, the server leaps into action, and attempts to send the data back to the client. The server reads the data correctly but starts processing it only when I stop the client program.
This is the client code:
import java.io.*;
import java.net.*;
class ServerTest{
public static void main(String args[]) throws Exception{
Socket clientSocket = new Socket(myIpAdress, 8001);
//Send the message to the server
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String sendMessage = "randSubstring:StackOverflowIsAwsome";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent: "+sendMessage);
String message = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())).readLine();
System.out.println("Message received from the server : " +message);
clientSocket.close();
}
}
My server code consists of two classes. This one is the listener:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerListener {
public static void main(String args[]) throws Exception {
String clientSentence;
ServerSocket socket = new ServerSocket(8001);
while(true) {
Socket connectionSocket = socket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
//DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = input.readLine();
if(clientSentence.startsWith("randSubstring:")){
Thread connection = new Thread(new ServerConnection(connectionSocket, clientSentence));
connection.start();
}
Thread.sleep(300);
}
}
}
This is the thread that will not start until the client is stopped:
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Random;
public class ServerConnection implements Runnable{
private Socket serverConnection;
private String sentence;
public ServerConnection(Socket connection, String clientSentence){
serverConnection = connection;
sentence = clientSentence;
}
#Override
public void run() {
Random r = new Random();
String substring = sentence.substring(0, r.nextInt(sentence.length()));
try {
OutputStream os = serverConnection.getOutputStream();
OutputStream out = new BufferedOutputStream(os);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write(substring);
bw.close();
out.close();
os.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am using a Macintosh with Yosemite. Is this happening because I am trying to run the programs on the same computer, or would the problem occur if the programs were run from different computers? Any help is appreciated.
In the server you do a readLine(..), which means that it will wait for a end-of-line character.
But in your sender code, you just send a string with no line ending.
So either you make sure you also send a end of line char or your server wait's for something else as "delimiter"
You're reading a line but you aren't writing a line. Add a line terminator to the sent message. Otherwise readLine() won't return until the peer closes the connection.
NB The I/O in the try block after the accept should be in the Runnable, not where it is. Don't do I/O in the accept loop.
How do you code a chat client so that it listens for input both from the server and from the console? This is my current client which successfully sends to and accepts input from the server. As you can see, it doesn't have any code that will enable it to successfully listen for and accept input from the console while also being open to input from the server. The server input would be messages from other chat clients. A message sent from any chat client is broadcast to all other clients. I am pretty new to Java and am completely stuck even though I have a feeling the answer will be depressingly obvious.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClientMain
{
public static void main(String[] args) throws UnknownHostException, IOException
{
//DNS of Chat Server
final String HOST = "localhost";
//Port number for chat server connection
final int PORT = 6789;
Socket serverSocket = new Socket(HOST, PORT);
try
{
//Will need three streams for communication: console-client, client-server, server-client
PrintWriter toServer = new PrintWriter(serverSocket.getOutputStream(), true);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
//User must be logged in; any username is acceptable
System.out.print("Enter username > ");
toServer.println("LOGIN " + fromUser.readLine());
String serverResponse = null;
while((serverResponse = fromServer.readLine()) != null)
{
System.out.println("Server: " + serverResponse);
if(serverResponse.equals("LOGOUT"))
{
System.out.println("logged out.");
break;
}
System.out.print("command> ");
toServer.println(fromUser.readLine());
}
toServer.close();
fromServer.close();
fromUser.close();
serverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
If your main thread is listening to the input from the server, you may start another thread that would keep listening for input from the console. You will have to ensure that you handle input properly. Some flag may be set to indicate if the input is from the server or from the console.
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.