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) {
try {
s = new Socket("192.168.1.*", 2001);
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