Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to 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
 
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
 

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 4-Feb-13 2:24am
GaryDoo435

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
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)
  Permalink  
Comments
GaryDoo at 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 at 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 at 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 at 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)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 434
1 OriginalGriff 385
2 CHill60 230
3 CPallini 220
4 Abhinav S 200
0 Sascha Lefévre 75
1 OriginalGriff 70
2 F-ES Sitecore 55
3 Peter Leow 50
4 Dave Kreskowiak 40


Advertise | Privacy | Mobile
Web02 | 2.8.150327.1 | Last Updated 8 Feb 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100