I planed to connect my android application as a client with server but I do not know where can I write the code in android activity because I have number of activities ,also I need you guys to explain the port number can I change it ? if I can depend in what?
client:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SimpleClientActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private EditText ipField;
private Button button;
private String messsage;
private String serverIp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1); //reference to the text field
button = (Button) findViewById(R.id.button1); //reference to the send button
ipField=(EditText) findViewById(R.id.editText2);
//Button press event listener
button.setonclickListener(new View.onclickListener() {
public void onclick(View v) {
messsage = textField.getText().toString(); //get the text message on the text field
textField.setText(""); //Reset the text field to blank
serverIp=ipField.getText().toString();
try {
client = new Socket(serverIp, 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) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); //Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
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) {
System.out.println("Problem in message reading");
}
}
}
}
You can create a separate Thread your Server. And in case you need reference of your activity, you can pass instance of same to it to handle callback.
You can create a server on ports 1 through 65535, until unless it is occupied by any other app.
Let me know, if it solves your problem.
You can try with asynctask and a http get post request like the example herequestion answered by #Hubert very well .If you need to work with socket try to look here and here, hope it helps
Related
I'm creating an simple app, in which I want to send message over local wifi connection using TCP. So I'm creating hotspot on one device and connect it from other device.
Now, on hosting device, I'm running following server application and on connecting device I'm running client application.
But nothing happens when I press send button on client device. My code for both server and client is as following:
Code for server:
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
Code for client:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
private Socket socket;
private String TAG="XXX";
private static final int SERVERPORT = 5000;
private String SERVER_IP ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
SERVER_IP = getWifiApIpAddress();
}
public String getWifiApIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
if (intf.getName().contains("wlan")||intf.getName().contains("ap")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& (inetAddress.getAddress().length == 4)) {
Log.d(TAG, inetAddress.getHostAddress());
return inetAddress.getHostAddress();
}
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
// out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I'm following this tutorial. As explained there, It is working fine in android emulators. But doesn't work on actual devices.
So I thought the IP address should be given different on different hotspots. So I've written a method in client code to get server hotspot's IP address and than connect to it. But still nothing happens on pressing send button.
So, What am I missing here? Is my method correct? Is there any mistakes in port numbers?
In the tutorial, author is doing something called port forwarding. What about port forwarding for actual devices?
I've searched everywhere for this on Internet but can't find any exact solution or any tutorial explaining this type of application. Please help me!
EDIT:
when I run this in real devices, It is giving NllPointerException in clients code, on following line:
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
You don't need to forward anything on device, just make sure your device is on the same network & use the port you have hard-coded or defined in the settings.
We forward port in emulator because its running on your host machine & we are telling the host to forward traffic coming on that specific port to emulator, since in an actual device you don't need to do that so you just to have to make sure your device is on the same network & correct port is being called.
I googled and saw almost all stackoverflow solutions and android documentation but I was unable to do it. Here is my server side code:-
import socket
import time
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#host = socket.gethostname()
host = "192.168.1.100"
port = 6000
serversocket.bind((host,port))
serversocket.listen(5)
def sample1():
print "the data has arrived"
clientsocket.send("success")
def sample2():
print "the data"
clientsocket.send("success again")
while True:
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
while 1:
data3 = clientsocket.recv(1024)
data4 = data3.strip()
if data4 == "hello":
sample1()
elif data4 == "hi":
sample2()
else:
print "random data"
if data4 == "stop":
break
Here is my client code on android:-
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Main22Activity extends Activity {
private Socket socket;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "192.168.1.100";
TextView risp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
risp = (TextView) findViewById(R.id.display);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
new ConnectionTask().execute();
}
class ConnectionTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
String responce = null;
try {
String str = "hello";
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
out.flush();
InputStream input = socket.getInputStream();
int lockSeconds = 10*1000;
long lockThreadCheckpoint = System.currentTimeMillis();
int availableBytes = input.available();
while(availableBytes <=0 && (System.currentTimeMillis() < lockThreadCheckpoint + lockSeconds)){
try{Thread.sleep(10);}catch(InterruptedException ie){ie.printStackTrace();}
availableBytes = input.available();
}
byte[] buffer = new byte[availableBytes];
input.read(buffer, 0, availableBytes);
responce = new String(buffer);
out.close();
input.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return responce;
}
protected void onPostExecute(String responce) {
risp.setText(responce);
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
onClick event is triggered on clicking a button. All permissions firewall settings also checked they are fine. On opening the app, it connects to python server (it shows it received a connection). On clicking, it sends string hello first which makes it jump to sample1 function and android also receives message success in textView. But after that it doesn't stop and python server keeps on printing random data forever and nothing happens on clicking the button again. I want my client to send hello only once after it is pressed, get the data, update UI and wait until button is pressed again. And originally, I am using this for raspberry pi to get temperature data so each time temperature changes, python server will send data and I want to display it on my android app without need of pressing any button. How should I do the thing I originally intend to do? Corrected code will be appreciated. Thanks.
Trying to do android socket programming based on this tutorial
http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/
I have my firewall turned off and anti virus disabled. If I make my server address to 127.0.0.1 I get the error in the title. If I make it my local IP address,it just sits at socket going to be created.I have tried it without and with port forwarding and setting it to the same port.
Client
package com.bennatpjose.androidsocketclient;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private Socket socket;
private TextView text;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.52.7.179";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
text.setText(text.getText().toString()+"Client Thread should be fired");
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
text.setText(text.getText().toString()+"\n"+"Click Event "+str);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
text.setText(text.getText().toString()+"\n"+"Next is out.println("+str+")");
out.println(str);
text.setText(text.getText().toString()+"\n"+"out.println("+str+")");
} catch (UnknownHostException e) {
text.setText(text.getText().toString()+"\nPrint Writer UnknownHostException "+e.toString());
} catch (IOException e) {
text.setText(text.getText().toString()+"\nPrint Writer IOException "+e.toString());
} catch (Exception e) {
text.setText(text.getText().toString()+"\nPrint Writer Exception "+e.toString());
}
}
class ClientThread implements Runnable {
#Override
public void run() {
text.setText(text.getText().toString()+"\nInside client thread run method ");
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
//If I set address to my local ip it just sits here and doesn't show socket created.
text.setText(text.getText().toString()+"\n"+serverAddr +" Socket going to be Created");
socket = new Socket(serverAddr, SERVERPORT);
text.setText(text.getText().toString()+"\n"+socket.toString() +"Socket Created");
} catch (UnknownHostException e1) {
text.setText(text.getText().toString()+"\nClient Thread UnknownHostException "+e1.toString());
} catch (IOException e1) {
text.setText(text.getText().toString()+"\nClient Thread IOException "+e1.toString());
}catch (Exception e1) {
text.setText(text.getText().toString()+"\nClient Thread Exception "+e1.toString());
}
}
}
}
Server
package com.bennatpjose.androidsocketserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text2);
text.setText(text.getText().toString()+"onCreate method started");
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
text.setText(text.getText().toString()+"\n"+"serverThread started");
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
text.setText("!!Socket Stopped!!");
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
text.setText(text.getText().toString()+socket+"\n");
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
So I figured it out. One of the mistakes I did was replacing the SERVER_IP with my local ip where as I should have left it at 10.0.2.2 since its a special loopback address android emulators.
10.0.2.2 Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
You also have to run the server first,set the port redirection and then run the client.
Look up Emulator networking section at http://developer.android.com/tools/devices/emulator.html
I have a problem sending something back from server to the client.
this code only send data from the android client to the server and i can't make it send something back from the server to the android client. I tried putting Inputstream reader in the client code and it seems not to work.
and here is the code:
Client Code:
package com.lakj.comspace.simpletextclient;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* This is a simple Android mobile client
* This application read any string massage typed on the text field and
* send it to the server when the Send button is pressed
* Author by Lak J Comspace
*
*/
public class SlimpleTextClientActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slimple_text_client);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
client = new Socket("10.0.2.2", 4444); // connect to the 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) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.slimple_text_client, menu);
return true;
}
}
Server Code:
package com.lakj.comspace.simpletextserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
* This is a simple server application. This server receive a string message
* from the Android mobile phone and show it on the console.
* Author by Lak J Comspace
*/
public class SimpleTextServer {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
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) {
System.out.println("Problem in message reading");
}
}
}
}
Sockets are "bi-directional". You need to getInputStream on the client side and getOutputStream on the server side on the same port/socket.
Add to client:
client = new Socket(IP, PORT); // second connection to server
inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
inputStreamReader.close();
socket.close(); //closing the connection
& To server:
printWriter = new PrintWriter(clientSocket.getOutputStream(), true);
printWriter.write("Returned back from server to client \n"); //write the message to output stream
printWriter.flush();
printWriter.close();
inputStreamReader.close();
clientSocket.close();
I am trying to develop an Android application but I am running into some problems trying to get my phone to connect to my server. Originally when trying to connect to my Server I got an IOException which I finally resolved by putting permissions in the manifest. Now I am getting an Socket Exception: "Connection Refused", I am completely sure that the Server is listening as I can run another program on my computer in just plain java that connects to the server and it works fine. I have run the client application on both the emulator and my actual phone (on my WiFi network) with both the IP address of my computer and "localhost". My question is if anyone has an idea as of why this is happening. This is some of the code:
Client:
package com.patyo.money4free;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Tutorial_Accountname extends Activity{
Button bSubmit;
EditText Account,ConfirmAccount;
TextView ErrorText;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial_accountname);
bSubmit = (Button) findViewById (R.id.AccountNameSubmitButton);
Account = (EditText) findViewById (R.id.AccountName);
ConfirmAccount = (EditText) findViewById (R.id.ConfirmAccountName);
ErrorText = (TextView) findViewById (R.id.AccountNameErrorText);
if(!TutorialGolbals.Username.equals(""))
{
Account.setText(TutorialGolbals.Username);
ConfirmAccount.setText(TutorialGolbals.Username);
}
bSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = Account.getText().toString();
String confusername = ConfirmAccount.getText().toString();
if(username.equals(confusername)){
if(username.equals(""))
{
ErrorText.setTextColor(Color.RED);
ErrorText.setText("Username Field is Empty!");
}else{
ErrorText.setText("Testing Account...");
BufferedReader in = null;
PrintWriter out = null;
Socket connection = null;
try {
//This is where it throws exception
connection = new Socket(Server_Globals.address,Server_Globals.port_create);
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
out = new PrintWriter(connection.getOutputStream(), true);
} catch (UnknownHostException e) {
ErrorText.setTextColor(Color.RED);
ErrorText.setText("Sorry, Cannot Connect to Server");
return;
} catch (IOException e) {
ErrorText.setTextColor(Color.RED);
ErrorText.setText("Sorry, Cannot Connect to Server");
return;
}
String s = "";
s+="Try Account\r\n";
s+=username+"\r\n";
out.write(s);
out.flush();
boolean reading = true;
String response = null;
try {
while(reading){
if(in.ready())
{
response = in.readLine();
reading = false;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
reading = false;
ErrorText.setTextColor(Color.RED);
ErrorText.setText("Sorry, Cannot Connect to Server");
}
if(response.equals("TRUE")){
Intent nextArea = new Intent("com.patyo.money4free.TUTORIALEMAIL");
TutorialGolbals.Username = username;
startActivity(nextArea);
}
else if(response.equals("FALSE")){
ErrorText.setTextColor(Color.RED);
ErrorText.setText("Someone Already Has That Username!");
}
}
}else{
ErrorText.setTextColor(Color.RED);
ErrorText.setText("Usernames are Not the Same!");
}
}
});
}
}
The Part of the Server that looks for connections:
package com.patyo.money4free.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Lookout_CreateAccount {
private static final int port = 5222;
public static void main(String[] args) {
ServerSocket server = null;
Socket buffer = null;
try {
server = new ServerSocket(port);
System.out.println("Server Started...");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(-1);
}
while(true)
{
try {
buffer = server.accept();
System.out.println("Server Accepted Client");
Thread buff = new Thread(new CreateAccountHandler(buffer));
buff.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The connection refused can be caused by a firewall, if i was you i would try disabling the firewall on your server and try it again, i had the same problem untill i ran my server on an open ipadress