I Can't read from the server-side socket - java

First of all, the android application will connect to the server (PC).
Then the android will send a message.
And finally the android application should receive a message from the server.
When I send the message from the android to the Server, everything goes well.
However, when it comes to reading from socket inside the android app, I can't receive anything.
Here is the Server code
ServerSocket Sock = new ServerSocket(7777);
System.out.println("Waiting for connection...\n");
Socket connectionSocket = Sock.accept();
System.out.println("Client In...");
BufferedReader inFromClint = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter printwriter = new PrintWriter(connectionSocket.getOutputStream());
String txt = inFromClint.readLine();
System.out.println(txt);
String MsgToClient = "{\"LoginFlag\":\"N\"}"; //{"LoginFlag":"P"}
printwriter.write(MsgToClient);
printwriter.flush();
printwriter.close();
System.out.println("\nMsg Sent");
Sock.close();
And this is sample of the Android app:
new Thread(new Runnable() {
#Override
public void run() {
try
{
BufferedReader bufferedReader = null;
PrintWriter printwriter = null;
port = 7777;
client = new Socket("192.168.1.2", port);
printwriter = new PrintWriter(client.getOutputStream());
printwriter.write(SMsgLog);
printwriter.flush();
printwriter.close();
bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
if( bufferedReader.ready() )
{
RJasonLog = bufferedReader.readLine(); //rcv as jason
}
else
{
RJasonLog = null;
}
if (RJasonLog != null)
{
JSONObject objectRcv = new JSONObject(RJasonLog);
if (objectRcv != null)
{
RMsgLog = objectRcv.getString("LoginFlag"); //Jason Key from the server
}
}
RMsgLog = "N";
if(RMsgLog.equals("N"))
{
alert.showAlertDialog(Login.this, "Login failed..", "Username/Password is incorrect", false);
}
else
alert.showAlertDialog(Login.this, "Login failed..", "Please Try Again", false);
client.close();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();

The clienr is trying to read a line. But the server is not sending a line with printwriter.write(MsgToClient);. Change to printwriter.write(MsgToClient + "\n"); to send a line.

I solved it with the help from the comments.
I removed printwriter.close(); on client side.
And then I added \n In both client and server before sending the message

Don't close the output stream in client code, Remove this line:
printwriter.close();
Stream should not be closed until connection is alive. It should be closed at the end when you are done with the socket. Closing connection will also close the streams associated with it.
Here is small description about the getOutputStream method.
getOutputStream
public OutputStream getOutputStream() throws IOException Returns an
output stream for this socket. If this socket has an associated
channel then the resulting output stream delegates all of its
operations to the channel. If the channel is in non-blocking mode then
the output > stream's write operations will throw an
IllegalBlockingModeException.
Closing the returned OutputStream will close the associated socket.
Returns: an output stream for writing bytes to this socket. Throws:
IOException - if an I/O error occurs when creating the output stream
or if the socket is not connected.

Related

Java Socket Communication "deadlock"

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);

Can't send multiple messages via socket

I'm trying to make a little chat system. I have a console and a client. Right now only the client need to send messages to the console. I can connect successfully to the server, and i can send one message from client to console. The trouble begins after sending the first message. When the first message i can't send any other messages.
I don't know if it's the console that won't read the message or the client that won't send the message. In this case how could i troubleshoot this?
public class ClientMainClass {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
Scanner scanner = new Scanner(System.in);
System.out.println("Skriv dit username:");
String name = scanner.nextLine();
System.out.println("Du er logget ind som: " + name);
String input;
do{
input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("Du forlod serveren");
socket.close();
continue;
}else {
/*OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);*/
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
Date date = new Date();
String time = date.getDate()+"/"+date.getMonth()+":"+date.getHours()+":"+date.getMinutes();
//Send the message to the server
String message = time+ " - " + name + ": "+input;
printWriter.println(message);
System.out.println(message);
continue;
}
}while (!(input.equals("exit")));
} catch (Exception exception) {
exception.printStackTrace();
} finally {
//Closing the socket
try {
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
My server:
public class Main{
private static Socket socket;
public static void main(String[] args) {
try {
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
System.out.println(br.readLine());
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch(Exception e){}
}
}
}
To be clear. I can connect to the server. I can send one message from client to console, but no more than one message.
You never read a second line. Your Server accepts a connection, reads one line from that connection and then waits for a new connection, discarding everything that might arrive at the first connection.
Your client however sends all input using the first (and only) connection, which is absolutely correct.
This specific problem can be solved like this:
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while(true){
System.out.println(br.readLine());
}
}
This will cause your program to print everything arriving on that first connection, but it will never accept a second connection.
In order to handle multiple clients, you need a Thread to deal with each one.

java Socket programming Server Client

I'm trying to program a Server Client program where the CLIENT will be prompt if the SERVER closes or loses connection. What happens is once I connect the server and the client then disconnects the server it doesn't go to the ConnectException part
example: I opened the Server and Client connects, in the Client it will show that "You are connected to the Server", then if the Server disconnects there should be a "Server is disconnected". and when the Server reopens it will prompt the Client that he's connected to the Server
How can I continuously check if the Server is open or disconnected
here's my code:
SERVER
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
System.out.println("Client has connected!");
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
CLIENT
public class Client
{
private static Socket socket;
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
System.out.println("Connected to the Server");
}
catch (ConnectException exception)
{
System.out.println("Server is still offline");
}
catch(IOException ex)
{
System.out.println("Server got disconnected");
}
}
}
Well, the best way to tell if your connection is interrupted is to try to read/write from the socket. If the operation fails, then you have lost your connection sometime.
So, all you need to do is to try reading at some interval, and if the read fails try reconnecting.
The important events for you will be when a read fails - you lost connection, and when a new socket is connected - you regained connection.
That way you can keep track of up time and down time.
you can do like this
try
{
Socket s = new Socket("address",port);
DataOutputStream os = new DataOutputStream(s.getOutputStream());
DataInputStream is = new DataInputStream(s.getInputStream());
while (true)
{
os.writeBytes("GET /index.html HTTP/1.0\n\n");
is.available();
Thread.sleep(1000);
}
}
catch (IOException e)
{
System.out.println("connection probably lost");
e.printStackTrace();
}
or you can simply et connection time out like this socket.setSoTimeout(timeout); to check connectivity
or you can use
socket.getInputStream().read()
makes the thread wait for input as long as the server is connected and therefore makes your program not do anything - except if you get some input and
returns -1 if the client disconnected
or what you can do is structure your code in this way
while(isConnected())
{
// do stuffs here
}

Can't use the socket after relaunching it

I had create a new client-server connection using ordinary java socket programming:
private static BufferedReader input;
private static DataOutputStream output;
private static Socket socket;
public void connect() {
try {
socket = new Socket(address, port);
} catch (Exception e) {
e.printStackTrace();
}
}
And I'm sending and receiving the following way :
to send:
output = new DataOutputStream(socket.getOutputStream());
output.writeBytes(data);
to receive:
InputStream stream = null;
try{
stream = socket.getInputStream();
}catch(Exception e){
e.printStackTrace();
}
if(stream != null){
input = new BufferedReader(new InputStreamReader(
stream));
// some input processing
}
The problem is when The connection is interrupted some how I have to relaunch it again in the app run-time, so I made a thread in order to re-execute the connect() method, and It executed efficiently without any Exceptions, but then , the input and output variables fail to send or receive any data.
It sounds like you are reconnecting your socket without recreating your input and output streams.
Try running recreating your input and output streams after you run connect() like so:
output = new DataOutputStream(socket.getOutputStream());
stream = socket.getInputStream();
you can try cleaning the input and output stream in finally and also close the socket...
finally { socket.close(); }

how do i write on server and read on android

i want to create a printwriter in my java server and a buffertreader in my android code. right know i can send a message from my android and read it on my java compiler but i want to do the oppsite aswell. read on android and write on server. do i need two applications for that because i dont know if i can just put it in between try i each code?
android code:
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
java server:
while (true) {
try {
clientSocket = serverSocket.accept(); //accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
thank you for taking your time to read my problem
Yes you can create two way communication between them, all you have to do is open an InputStream on the client side (Android) and Open an OutputStream on the Java Server Side, it can be achieved in the following manner:
android code:
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
InputStream in = client.getInputStream();
byte data[] = new byte[1024]
in.read(data); ///perform your reading operation here
client.close(); //closing the connection
} catch (UnknownHostException e) {
java server:
while (true) {
try {
clientSocket = serverSocket.accept(); //accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
pw.write(new String("write data here"));
pw.flush();
pw.close();
clientSocket.close();
} catch (IOException ex) {

Categories