how do i write on server and read on android - java

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

Related

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.

I Can't read from the server-side socket

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.

Not printing files content in socket programming

I am naive to this socket programming. I am trying to print the content of the file present in the directory in the server's console but the server is not able to locate the file.
Here is my code:
myClient.java
import java.net.*;
import java.io.*;
public class myClient {
public static void main(String args[]){
Socket socket = null;
String hostName,command,fileName;
int port;
if(args.length == 0){
System.out.println("Error: command line arguments (hostname,port,command,"
+ "filename) not found.\nTry again...!!!");
System.exit(1);
}
hostName = args[0];
port = Integer.parseInt(args[1]);
command = args[2];
fileName = args[3];
try{
socket = new Socket(hostName,port);
System.out.println("Client Socket Created..!!");
// creating input and output streams to read from and write to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
if(command.equals("GET")){
System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
bw.write(fileName);
String line = br.readLine();
while(line != null){
System.out.println("Server: "+line);
line = br.readLine();
}
}
if(command.equals("PUT")){
System.out.println("Client: "+fileName+" sent to server");
bw.write(fileName);
// pass the file contents
bw.flush();
System.out.println("Server: "+br.readLine());
}
}
catch(UnknownHostException uhe){
System.out.println("Unknown Host...!!!");
System.exit(1);
}
catch(IOException e){
e.printStackTrace();
}
finally
{
//Closing the socket
try{
socket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
myServer.java
import java.net.*;
import java.io.*;
public class myServer {
static Socket socket;
public static void main(String args[]){
try {
int port = Integer.parseInt(args[0]);
//String fileName = "";
ServerSocket server = new ServerSocket(port);
while(true)
{
System.out.println("Server started and listening on port "+port);
socket = server.accept();
System.out.println("received a connection :"+socket);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Echo server 1.1\n");
bw.flush();
String line = br.readLine();
while(line != null){
bw.write("Echo: "+line);
bw.flush();
line = br.readLine();
}
}
} catch (IOException e) {
System.out.println("No conncetion established");
System.exit(0);
//e.printStackTrace();
}
finally
{
//Closing the socket
try{
socket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
Kindly help me out finding a solution to this. I have tried many examples browsing different websites but not get to the solutions.
System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
bw.write(fileName);
You aren't writing a correct HTTP command to the server. You're only sending the filename, not a complete command such as the GET command you're printing to the console.
The line terminator in HTTP is specified as \r\n, not \n.
You're also making no attempt to implement other aspects of HTTP 1.1 correctly, such as content-length. If you're going to implement HTTP you need a good knowledge of RFC 2616.
If possible you should throw this away and use HttpURLConnection.

BufferReader.readline() block PrinterWriter.println()

After creating socket connection in Android App, i can't write in buffer after reading.
This is an example for establishing connection with my Server:
//...
try{
socket = new Socket(IP, Port);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
//ask for connection
out.println(req1);
//server send me a nonce
result=in.readLine().toString();
//encrypting nonce with specific alghorithm
passwd=Password.get_Passwd(result);
//sending password
out.println(passwd); //here out.println doesn't write
//...
} catch (IOException e){
e.printStackTrace();
} finally {
try {
socket.close();
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//...
So can any one help me solving this problem. Thanks.

java Simple Server Client program

I'm trying to build a simple server client program, I'm trying to figure a way how to prompt the CLIENT if the server is down, or if the server is up and loses connection
Question: How can I prompt the client that he's disconnected because the Server shuts down or loses connection
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);
while(true)
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//System.out.println("You're now connected to the Server"); /*this should only print once */
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number;
number=input.next();
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (IOException exception)
{
//System.out.println("Server is still offline");/*This should only print once*/
}
How can I prompt the client that he's disconnected because the Server shuts down or loses connection?
You can use the catch block to prompt the client in Client class which will be executed when IOException occurs
} catch (ConnectException e) { //When the connection is refused upon connecting to the server
//promt the user here
System.out.println("Connection refused");
break; //to quit the infinite loop
} catch (IOException e) { //when connection drops, server closed, loses connection
//promt the user here
System.out.println("Disconnected from server");
break; //to quit the infinite loop
}

Categories