I want to write a client-sever program in which server and client send messages to each other. First, my server send a message to client, then the client reply. Next, my server send another message, the client reply. The problem is, on my first message induced by the server, the client does not respond.
My server:
public class Server {
public void go() {
try {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server listening ...");
Socket socket = serverSocket.accept();
try (
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String input;
printWriter.println(new Scanner(System.in).nextLine());
while ((input = bufferedReader.readLine()) != null) {
System.out.println(input);
printWriter.println(new Scanner(System.in).nextLine());
if(input == "Bye") break;
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.go();
}
}
My client:
public class Client {
public void go() {
try {
try (
Socket socket = new Socket("localhost", 9999);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String input;
while ((input = bufferedReader.readLine()) != null) {
System.out.println("1");
System.out.println(input);
printWriter.println(new Scanner(System.in).nextLine());
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
client.go();
}
}
Are there some problems with my code?
Your client connects and then blocks reading a line from the server.
Your server accepts the connection and then blocks reading a line from the client.
I don't know what you were expecting to happen next, but it won't. Somebody needs to send something.
Your code seems to be fine. You just need to push the infrastructure by calling flush() after writing:
printWriter.flush();
Related
I am trying to build a simple multi client chat application using java sockets. The way I have gone about doing this is by having a client class that connects to a server class that waits for clients to connect and creates a new thread to deal with that client(Where the socket connection is read and written to). The client also reads from and writes to the socket connection to this thread. However, when the client wrote to the output stream of the socket, the server would not respond. A similar question here was posted:
Can you write to a sockets input and output stream at the same time?
One of the answers here says that you can read and write to a socket at the same time as long as reading from the socket is done on a separate thread.
Here is my client application:
public class Client {
Socket socket;
public static void main(String[] args) {
new Client();
}
public Client() {
try {
socket = new Socket("localhost", 4444);
new Thread() {
#Override
public void run() { //read from the input stream
try(
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String line;
while( (line = in.readLine()) != null ) {
System.out.println("Server said: " + line);
}
} catch(IOException e) {
}
}
}.start();
//write to output stream
try(
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner userInput = new Scanner(System.in);
){
System.out.println("Enter Something: ");
if(userInput.hasNextLine()) {
out.println(userInput.nextLine());
}
} catch (IOException e) {
}
} catch(IOException e) {
}
}
}
And my server application:
public class Server {
ServerSocket ss;
public static void main(String[] args) {
new Server();
}
public Server() {
System.out.println("Server Running...");
try {
ss = new ServerSocket(4444);
while(true) {
Socket socket = ss.accept();
new Thread() { //create new thread connection to client
#Override
public void run() {
new Thread() { //thread that reads inputstream
#Override
public void run() {
try(
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String line;
while( (line = in.readLine()) != null ) {
System.out.println("Client said: " + line);
//The problem seems to lie here.
}
} catch(IOException e) {
}
}
}.start();
//write to outputstream
try (
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
) {
String sendToClient = "Hey, my name is Server007 B)";
out.println(sendToClient);
} catch(IOException e) {
}
}
}.start();
}
} catch (IOException e) {}
}
}
I will run the server, then run the client, on the client side the output is
Server said: Hey, my name is Server007
Enter something:
Hello! <- enter anything
but the server does not print 'Client said: Hello!' like I expected it to. I hope I made my problem clear enough, thanks.
Ok, so I figured it out, I will answer my own question in case anyone makes the same mistake. The PrintWriter constructor should be this:
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Not this:
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
Alternatively, I could have done this:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
I must have just gotten confused between BufferedWriter and PrintWriter :P
Hi I am trying to implement server operating with multiply clients
The problem is that the server does not receive the message from inputstream and wait until it happen. if the client don't close the stream after writing to it the server will continue to wait. After the client send the message, he try to read from the inputstream waiting for response, but the server is waiting for the request. So.. deadlock
This is my client class
public class Client implements Runnable{
...
#Override
public void run() {
BufferedReader is = null;
BufferedWriter os = null;
try(Socket socket = new Socket(address.getHostName(), address.getPort());){
String request = String.format("%s-%d-%s",this.destination, this.desiredPlace, this.paymentMethod.toString());
os = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(os, true);
pw.write(request);
pw.flush();
// if I close the stream here the request will be send, but this will close the socket so the I will not receive response.
String response;
while ((response = is.readLine()) != null){
System.out.println(response);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And this is my server class
public void perform() throws IOException, DestionationProcessingException, InterruptedException {
try (ServerSocket server = new ServerSocket(port);) {
StandalonePayDesk offLinePayDesk = new StandalonePayDesk(ticketManager);
this.threadPool.submit(offLinePayDesk);
while (true) {
Socket socket = server.accept();
RequestHandler handler = new RequestHandler(this.threadPool, offLinePayDesk, this.ticketManager);
handler.process(socket);
}
}
}
and RequestHandler class for processing each client
try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter writer = new PrintWriter(client.getOutputStream(), true)) {
writer.println("hello");
writer.flush();
String line;
while ((line = reader.readLine()) != null) {
String[] lineTokens = line.split("-");
...
Can anyone help me to solve this problem ?
pw.write(request);
Your client is writing a request but not a line. Your server is reading a line, with readLine(), and will block until the line terminator arrives, which is never, so it will never send a reply, so your client will never receive it, so it will block forever.
Change the above to:
pw.println(request);
I am trying to figure out why I can send messages to the client from the server but when I try the other way around (to send messages from the client to the server) the program halts like it is waiting for some action to happen.
also how to prevent the sockets from being closed immediately.
this is the code:
Client Class
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
Client aClient = new Client();
aClient.run();
}
private Socket socket;
private PrintWriter toServer;
private BufferedReader fromServer;
public void run() {
try {
socket = new Socket("localhost", 9000);
if (socket.isConnected()){
System.out.println("CONNECTED");
}
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer = new PrintWriter(socket.getOutputStream());
toServer.print("hello server");
System.out.print(fromServer.readLine());
toServer.close();
socket.close();
} catch (Exception error) {
System.out.println("CLIENT ERROR: " + error);
}
}
}
Server Class
import java.io.*;
import java.net*;
public class Server {
public static void main(String[] args) {
Server aServer = new Server();
aServer.run();
}
private ServerSocket mainSocket;
private Socket socket;
private PrintWriter toClient;
private BufferedReader fromClient;
public Server(){
try{
mainSocket = new ServerSocket(9000);
}
catch (Exception error){
System.out.print("Error :"+error);
}
}
public void run() {
System.out.println("WAITING FOR CLIENTS");
try {
socket = mainSocket.accept();
if(socket.isConnected()) {
System.out.println("CONNECTED.");
}
fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toClient = new PrintWriter(socket.getOutputStream());
System.out.println(fromClient.readLine());
toClient.print("hello Client");
toClient.close();
}
catch (Exception error) {
System.out.println("SERVER ERROR :" + error);
}
}
}
Add this before toServer.print("hello server"); to Client class. Its read from System.in and send to the Server class:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromUser;
while((fromUser = stdIn.readLine()) != null) {
System.out.println("Client: " + fromUser);
toServer.println(fromUser);
}
And to Server class add this, before System.out.println(fromClient.readLine());, its read line from client and print to System.out:
String inputLineFromClient;
while ((inputLineFromClient = fromClient.readLine()) != null) {
System.out.println(inputLine);
}
Socket not closing before you invoke method close() or occurs some Exception.
your server is not reading anything.
use
fromClient.readLine();
I have a client class and a server class.
If client sends message to server, server will send response back to the client, then client will print all the messages it received.
For example,
If Client sends "A" to Server, then Server will send response to client
"1111". So I use readLine() in client class to read the message from server, then client print "1111" in the console.
If Client sends "B" to Server, then Server will send response to client
"2222\n 3333". So the expected printing output from client is:
"2222"
"3333"
So the response message from server to client may have 1 line or 2 lines depending on the message it send from client to server.
My question is that how I can use readLine() to read the message that send from server to client. More specifically, if I use the following codes,
String messageFromServer;
while(( messageFromServer = inputStreamFromServer.readLine()) != null) {
println(messageFromServer);
}
It will only print the first line, and will not print anything else even if I keep sending message from client to server, because readLine() will stops once it has read the first line.
update:
More specifically, I am looking for some methods in the client class to read message that contains 1 or multiple lines from server at a time. I am wondering if there are any ways to do it in client side if I don't want to change the format of the message that sent from server to client.
update 2
To make my question more clear, I will put some sample codes in the following:
This is server:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(1234);
} catch (IOException e) {
System.err.println("Could not listen on port: 1234.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
}
System.out.println("Connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String textFromClient =null;
String textToClient =null;
textFromClient = in.readLine(); // read the text from client
if( textFromClient.equals("A")){
textToClient = "1111";
}else if ( textFromClient.equals("B")){
textToClient = "2222\r\n3333";
}
out.print(textToClient + "\r\n"); // send the response to client
out.flush();
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
The client:
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try {
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
}
System.out.println("Connected");
String textToServer;
while((textToServer = read.readLine())!=null){
out.print(textToServer + "\r\n" ); // send to server
out.flush();
String messageFromServer =null;
while(( messageFromServer = textToServer=in.readLine()) != null){
System.out.println(messageFromServer);
}
}
out.close();
in.close();
read.close();
socket.close();
}
private static void debug(String msg)
{
System.out.println("Client: " + msg);
}
}
You shouldn't need to change the format of the data sent by the server, and readLine() should work, but I suspect that the server is not flushing or closing the OutputStream after writing the response which could possibly explain things.
Is the call to readLine() hanging? Are you in control of the server code? If so, can you include it?
Revised classes that work as I believe you expect:
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 ClientServerTest2
{
public static void main(String[] args) throws Exception
{
Thread serverThread = new Thread(new Server());
serverThread.start();
Thread clientThread = new Thread(new Client());
clientThread.start();
serverThread.join();
clientThread.join();
}
private static class Server implements Runnable
{
#Override
public void run()
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(1234);
Socket clientSocket = null;
clientSocket = serverSocket.accept();
debug("Connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String textFromClient = null;
String textToClient = null;
textFromClient = in.readLine(); // read the text from client
debug("Read '" + textFromClient + "'");
if ("A".equals(textFromClient))
{
textToClient = "1111";
}
else if ("B".equals(textFromClient))
{
textToClient = "2222\r\n3333";
}
debug("Writing '" + textToClient + "'");
out.print(textToClient + "\r\n"); // send the response to client
out.flush();
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void debug(String msg)
{
System.out.println("Server: " + msg);
}
}
private static class Client implements Runnable
{
#Override
public void run()
{
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
try
{
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
debug("Connected");
String textToServer;
textToServer = read.readLine();
debug("Sending '" + textToServer + "'");
out.print(textToServer + "\r\n"); // send to server
out.flush();
String serverResponse = null;
while ((serverResponse = in.readLine()) != null)
debug(serverResponse); // read from server and print it.
out.close();
in.close();
read.close();
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private static void debug(String msg)
{
System.out.println("Client: " + msg);
}
}
Change while(( messageFromServer = inputStreamFromServer.readLine() != null) to while(( messageFromServer = inputStreamFromServer.readLine()) != null)
Actually this shouldn't even compile....
It's a work around.
If you want to send multiple strings like in your case : "2222\n 3333".
You can send them by adding a seperator character (like :) between two strings : "2222: 3333".
Then you can call write from server side as
clientOut.write("2222: 3333\n");
On client side parse recieved String :
messageFromServer = inputStreamFromServer.readLine();
String strArray[] = messageFromServer.split(":");
strArray[0] : 2222
strArray[0] : 3333
I have two Java applications, where an Android client connects to a server on a computer and sends a message using BufferedWriter over websockets.
The client:
try {
toast("Sending...");
Socket sock = new Socket(ip, PORT);
OutputStream os = sock.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.flush();
bw.write("Hello Server!");
toast("Connected!");
} catch (UnknownHostException e) {
toast(e.getMessage());
} catch (IOException e) {
toast(e.getMessage());
}
The server:
public static void main(String[] args) {
ServerSocket server;
ConnectionThread ct;
Socket s;
ExecutorService es = Executors.newSingleThreadExecutor();
try {
System.out.println("Starting server...");
server = new ServerSocket(1337);
s = server.accept();
ct = new ConnectionThread(s);
es.execute(ct);
} catch (IOException ex) {
ex.printStackTrace();
}
}
The ConnectionThread class:
public class ConnectionThread implements Runnable {
private Socket sock;
private InputStream is;
private BufferedReader br;
private boolean online;
public ConnectionThread(Socket s) {
System.out.println("Creating connection thread.");
this.sock = s;
online = true;
}
#Override
public void run() {
String input = "";
try {
System.out.println("Starting to read...");
is = sock.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while (online) {
input = br.readLine();
if(input != null){
System.out.print("Received message: ");
System.out.println(input);
}
}
br.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I run the server, and then the client, the client will show the "Connected!" toast, and the server's output will be:
Starting server...
Creating connection thread.
Starting to read...
So, it seems like the connection is actually being made, but the message does not arrive. Does anybody know why this could be happening?
Your server is expecting a complete line terminated by a newline. Try:
bw.write("Hello Server!");
bw.newLine();
Do it like this...
String s = new String();
while ((br.readLine())!=null) {
s = s+br.readLine();
System.out.print("Received message: ");
System.out.println(input);
}
}
And
bw.println("Hello Server");
I notice that you don't send an endline on your client, so the BufferedReader.readline() will never return, because it cannot match the \n-character. Try it again with
bw.write("Hello Server!\n");
on the client side.