Click here to Skip to main content
15,881,880 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi,

I'm really hoping someone here can help me out. I'm working on an android project in college, I haven't done android programming, nor have I done any socket programming in college. My first step in this project is to have a client server communication. I have, based on notes and tutorials etc I have found online created a simple client and server, where a string is sent to the server when a button is clicked on the client side. This string is then mean to print to console...

I've included my code below, unfortunately, the string doesn't print to the console, it looks correct to me. Could someone please have a quick look over this and see where I might be going wrong?

I'm pulling my hair out at this stage!!


SERVER

Java
public class Additional_Server {  
  
    private static String message;  
  
    public static void main(String[] args) throws Exception {  
  
          
            Socket s;  
            ServerSocket ss = new ServerSocket(2001);  
              
              
        System.out.println("Server started. Listening to the port 2001");  
  
          
          
        while (true) {  
            try {  
                System.out.println("Server: waiting for connection ..");  
                  
                s = ss.accept();  
                InputStream in = s.getInputStream();  
                Scanner r = new Scanner(in);  
                OutputStream o = s.getOutputStream();  
                PrintWriter p = new PrintWriter(o);  
  
                String inputLine;  
                inputLine = r.nextLine();  
                p.println("Hello " + inputLine + " from Gary");  
                p.close();  
              
              
          
            } catch (IOException ex) {  
                System.out.println("Problem in message reading");  
            }  
        }  
  
    }  
}  


CLIENT


Java
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.io.PrintWriter;  
import java.net.Socket;  
import java.net.UnknownHostException;  
import java.util.Scanner;  
import android.app.Activity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
import android.widget.TextView;  
  
public class MainActivity extends Activity {  
  
    private Socket s;  
    private PrintWriter p;  
    TextView display;  
    Button test;  
  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        test = (Button) findViewById(R.id.test);  
        display = (TextView) findViewById(R.id.Sdisplay);  
  
        test.setOnClickListener(new View.OnClickListener() {  
  
            public void onClick(View v) {  
                // TODO Auto-generated method stub  
  
                try {  
                    s = new Socket("192.168.1.*", 2001); // connect to server  
                    OutputStream o = s.getOutputStream();  
                    PrintWriter p = new PrintWriter(o);  
                    InputStream in = s.getInputStream();  
                    Scanner r = new Scanner(in);  
  
                    p.println("Gary");  
                    p.flush();  
                      
                      
                } catch (UnknownHostException e) {  
                    e.printStackTrace();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        });  
  
    }  
}


Thanking you in advance

Regards,
Gary
Posted

1 solution

In your Server code, you are writing your answer to the socket itself.

You have two choices:
1. display the message on the server using
C#
System.out.println("Hello " + inputLine + " from Gary");

2. read the answer on the client and display it in a widget of your Activity.
You have to check for available data in the input stream, read the data, and convert to string before setting the text of the "display" widget (for example)
 
Share this answer
 
Comments
GaryDoo 8-Feb-13 9:05am    
@ Pascal-78

Thank you for your quick response, unfortunately I've been offline for the past few days. I have changed this, and unfortunately it still doesn't work. I've created a simple server and client in java, and it works, as both server and machine is on the same machine. So I'm wondering is there some other issue? I am very grateful for your help thus far, if you would have any thoughts I'd really appreciate it.

In this line I'm putting in the ip of the client(phone) and port number?
<pre>s = new Socket("192.168.1.3", 2001); </pre>

I just really want to make sure I'm correct on this as it's really giving me a headache and I'm not sure how to fix it :(

I'm reposting the server and client code below now that it's edited.

CLIENT

<pre>import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Client extends Activity {

private Socket s;
private PrintWriter p;
TextView display;
Button test;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test = (Button) findViewById(R.id.test);
display = (TextView) findViewById(R.id.Sdisplay);

test.setOnClickListener(new View.OnClickListener() {

//@SuppressWarnings("unused")
public void onClick(View v) {
// TODO Auto-generated method stub

try {
s = new Socket("192.168.1.3", 2001); // connect to server
OutputStream o = s.getOutputStream();
p = new PrintWriter(o);
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);

p.println("Gary");
p.flush();

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});

}
}</pre>

SERVER

<pre>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;



public class Additional_Server {

public static void main(String[] args) throws Exception {


Socket s;
ServerSocket ss = new ServerSocket(2012);

//serverSocket = new ServerSocket(2001); // Server socket


System.out.println("Server started. Listening to the port 2001");



while (true) {
try {
System.out.println("Server: waiting for connection ..");
s = ss.accept();
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
// OutputStream o = s.getOutputStream();
// PrintWriter p = new PrintWriter(o);

String inputLine;
inputLine = r.nextLine();
System.out.println("Hello " + inputLine + " from Gary");
// p.close();



} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}

}
} </pre>

Again, my thanks for any further help you or anyone can provide to me

Regards,
Gary
Pascal-78 8-Feb-13 11:43am    
You create the server socket on port 2012 but try to connect the phone on port 2001.
On the phone: you should create a socket (without specifying address and port) then you can use the "connect" function (you will have access to a timeout parameter in this function).
When I made some socket test with my phone (using Android 4), I have to do 2 things:
- allowed full internet access (with eclipse and the android developer plugin, you have to edit the xml file describing the requirement of your app)
- use the socket function in a new thread:
new thread(new Runnable({ @Override void Run() { } })).start();
GaryDoo 8-Feb-13 11:59am    
sorry Pascal, that was an error with me posting my code across, both ports are the same.

So I declare a socket on the client side like

Socket mySocket = new Socket();

After that I'm not sure, I can't seem to find much on the connect() function. Would you mind giving me a few more pointers? I'm sorry to be such a headache!
Pascal-78 8-Feb-13 14:58pm    
I used this code to connect my android program to a server on my PC:
socket = new java.net.Socket();
InetAddress address = InetAddress.getByName("192.168.1.10");
socket.connect(new InetSocketAddress(address, 2012/*port*/), 5000/*timeout 5s*/);

help on this method can be found here:
http://developer.android.com/reference/java/net/Socket.html#connect(java.net.SocketAddress, int)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900