android socket server programming - android

I want to connect via socket to my android app.but in server side(android app) I get java.net.SocketTimeoutException error and in client side I get java.net.ConnectException: Connection refused: connecterror.
what is my mistake? thank you
server (android app)
public class ServerSocketTask extends AsyncTask<Void, Void, String> {
final StackTraceElement se = Thread.currentThread().getStackTrace()[2];
private String data = null;
#Override
protected String doInBackground(Void... params) {
Log.d(se.getClassName() + "." + se.getMethodName(), "start");
try {
ServerSocket serverSocket = new ServerSocket(8989);
serverSocket.setSoTimeout(50000);
Socket socket = serverSocket.accept();
socket.setKeepAlive(true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int readed = in.read();
Log.d("","readed bytes : "+readed);
String line;
while ((line = in.readLine()) != null){
Log.i("","line : "+ line);
}
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ServerSocketTask.this.data = result;
}
public String getData() {
return data;
}
}
client
public static void main(String[] args) {
int port;
try (Socket socket = new Socket("192.168.240.105", 8989)) {
String customerId = "123";
String requestId = Configuration.getProperty("requestId");
ClientService result = new ClientService();
String makeRequest = result.objectToJson(customerId, requestId);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.write(makeRequest);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
my client can't connect to server and my server wait for connection.

When you construct ServerSocket(8989) you're binding to wildcard address of network interfaces available on android emulator/device.
However both Android emulator and real device has it's own network interface(s) and thus it's it's own IP addresses. Your client program (development machine) IP address is not the same as IP address of android emulator/device. In other words you cannot connect to the socket created in Android app because you're using wrong address.
This answer should guide you on how to find out the address.

Related

Android 6.0 cant create socket

I cant create a simple TCP connection to my server.
I created a AsyncTask to send messages, but it didn't work.
I added INTERNET and ACCESS_NETWORK_STATE to the permissions.
I don't know what else to try.
public class ServerCommunicator extends AsyncTask<String,Void,Void>{
public static String SERVER_IP = "192.168.2.148";
public static int SERVER_PORT = 1337;
public static String SERVER_PW = "adsfadsf";
public Context context;
#Override
protected Void doInBackground(String... params) {
//Create Command
CommandFactory cmdFactory = new CommandFactory();
Command cmd = cmdFactory.createCommand();
System.out.println("Cmd created..");
//-----
try {
System.out.println(SERVER_IP);
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
System.out.println("Created serverAddr "+ SERVER_IP);
Socket socket = new Socket(serverAddr,SERVER_PORT);
System.out.println("Socket created..");
//sends the message to the server
PrintWriter mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String msg2Send = Crypter.Encrypt(cmd.toString(), SERVER_PW);
sendMsgAsByteArr(socket, msg2Send);
Command recCmd = cmdFactory.extractCommandFromStr(receiveMsg(socket));
socket.close();
Toast.makeText(context, recCmd.id, Toast.LENGTH_LONG).show();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static void sendMsgAsByteArr(Socket socket, String msg) {
try {
socket.getOutputStream().write(msg.getBytes());
System.out.println("sent cmd..");
} catch (IOException e) {
e.printStackTrace();
}
}
private static String receiveMsg(Socket socket) {
String msg = "";
int c;
ArrayList<Byte> incoming = new ArrayList<Byte>();
try {
while((c = socket.getInputStream().read())!=-1) {
incoming.add((byte)c);
}
byte[] allBytes = new byte[incoming.size()];
for(int i = 0; i < incoming.size(); i++) {
allBytes[i] = incoming.get(i);
}
msg = new String(allBytes);
} catch (IOException e) {
e.printStackTrace();
}
return msg;
}
}
My program runs till Socket socket = new Socket(serverAddr, SERVER_PORT); then it stops. It doesn't show any stack trace or errors.
Any ideas?
I debugged your code, and while there were multiple issues, none were related to Android 6.
I created a simplified version of your code and got it working.
One issue is that your context reference was null, so I set it in the constructor.
Another issue is that you were trying to show a Toast on a background thread, which won't work.
Another issue was your send and receive methods, they didn't work for me.
Here's the simplified code that I got working with a TCP/IP server, tested on both Android 4.4.4 and Android 6.
You can take this and expand on it as needed:
public class ServerCommunicator extends AsyncTask<String,Void,String> {
public static String SERVER_IP = "11.222.33.444";
public static int SERVER_PORT = 1234;
public Context context;
public ServerCommunicator(Context c) {
this.context = c;
}
#Override
protected String doInBackground(String... params) {
try {
System.out.println(SERVER_IP);
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
System.out.println("Created serverAddr "+ SERVER_IP);
Socket socket = new Socket(serverAddr,SERVER_PORT);
System.out.println("Socket created..");
//sends the message to the server
PrintWriter mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String msg2Send = "{\"HelloWorld\", \"1234\"}";
mBufferOut.println(msg2Send);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String result = in.readLine();
System.out.println("result: " + result);
socket.close();
return result;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}

Android client getting all the inputStreamReader at the deco from the server

I'm asking for a little help here..
I made a Android app in order to get messages from a server. The app just have to show the server's messages and nothing else.
the thing is nothing is shown in the UI, all the messages are shown when I disconnect the server.
It's frustrating because the app get the data's, just don't show them before the disconnection of the server.
Here is my code :
public class SlimpleTextClientActivity extends Activity {
private TextView textView;
private Socket client;
private PrintWriter printwriter;
private BufferedReader bufferedReader;
//Following is the IP address of the chat server. You can change this IP address according to your configuration.
// I have localhost IP address for Android emulator.
private String CHAT_SERVER_IP = "192.168.2.2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slimple_text_client);
textView = (TextView) findViewById(R.id.textView1);
ChatOperator chatOperator = new ChatOperator();
chatOperator.execute();
}
/**
* This AsyncTask create the connection with the server and initialize the
* chat senders and receivers.
*/
private class ChatOperator extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
try {
client = new Socket(CHAT_SERVER_IP, 6666); // Creating the server socket.
if (client != null) {
printwriter = new PrintWriter(client.getOutputStream(), true);
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
} else {
System.out.println("Server has not bean started on port 4444.");
}
} catch (UnknownHostException e) {
System.out.println("Faild to connect server " + CHAT_SERVER_IP);
e.printStackTrace();
} catch (IOException e) {
System.out.println("Faild to connect server " + CHAT_SERVER_IP);
e.printStackTrace();
}
return null;
}
/**
* Following method is executed at the end of doInBackground method.
*/
#Override
protected void onPostExecute(Void result) {
Receiver receiver = new Receiver(); // Initialize chat receiver AsyncTask.
receiver.execute();
}
}
/**
* This AsyncTask continuously reads the input buffer and show the chat
* message if a message is availble.
*/
private class Receiver extends AsyncTask<Void, Void, Void> {
private String message;
#Override
protected Void doInBackground(Void... params) {
while (true) {
try {
if (bufferedReader.ready()) {
message = bufferedReader.readLine();
publishProgress(null);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
}
#Override
protected void onProgressUpdate(Void... values) {
textView.append( message + "\n");
}
}
}
Hope that someone have an idea because here... I don't x)
Simon !
EDIT :
So... I went to java to test my code (simplification with the System.out.println)
Here is my code :
public class MainClass {
public static void main(String[] args) throws Exception {
final Socket client;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
client = new Socket("192.168.2.2", 6666);
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
// create new buffered reader
br = new BufferedReader(inputStreamReader);
int value=0;
String monChar = null;
String maChaine = null;
//System.out.println(maChaine);
// reads to the end of the stream
while((value = br.read()) != -1)
{
// converts int to character
char c = (char) value;
maChaine = maChaine + c;
}
}catch(Exception e){
e.printStackTrace();
}finally{
// releases resources associated with the streams
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}
The thing is that I can't reach maChaine.
This does the same thing that before : I only can reach my String when the server is disconected.
If I put a "System.out.println(maChaine);" in my While it will print something at each rows and if I put it after it will only do something if the server is disconected.

How to create server to use chat room realtime (SignalR) in android

I am beginner in android xamarin. I want to use chat room realtime using SignalR. But i dont know what is "http://10.0.2.2:8081/echo" mean in this example. Is it a server???There are something in that server - like php file, database or something else???
hope your answer, thanks :D or anybody show me how to build a group chat application, please(use socket like :http://www.androidhive.info/2014/10/android-building-group-chat-app-using-sockets-part-1/ or SignalR in xamarin )
using System.Collections.Generic;
using Android.App;
using Android.OS;
using Android.Widget;
namespace SignalR.Client.MonoDroid.Sample
{
[Activity(Label = "SignalR.Client.MonoDroid.Sample", MainLauncher = true, Icon = "#drawable/icon")]
public class DemoActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
var messageListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, new List<string>());
var messageList = FindViewById<ListView>(Resource.Id.Messages);
messageList.Adapter = messageListAdapter;
var connection = new Connection("http://10.0.2.2:8081/echo");
connection.Received += data =>
RunOnUiThread(() => messageListAdapter.Add(data));
var sendMessage = FindViewById<Button>(Resource.Id.SendMessage);
var message = FindViewById<TextView>(Resource.Id.Message);
sendMessage.Click += delegate
{
if (!string.IsNullOrWhiteSpace(message.Text) && connection.State == ConnectionState.Connected)
{
connection.Send("Android: " + message.Text);
RunOnUiThread(() => message.Text = "");
}
};
connection.Start().ContinueWith(task => connection.Send("Android: connected"));
}
}
}
10.0.x.x is a private subnet (http://en.wikipedia.org/wiki/Private_network). In this example then it is talking about you running some kind of server system on your computer on port 8081.
http://10.0.2.2:8081/echo
10.0.2.2 is the ip of your server
8081 is the port on which server listening your request and give response on same port
echo is the automated generate respone which is given to you on every request with same request(String)
public static class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String s;
String red;
String loc;
public MyClientTask(String addr, int port,String msg){
dstAddress = addr;
dstPort = port;
loc=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
ObjectInputStream inputStream=null;
try {
SocketAddress socketAddress = new InetSocketAddress(dstAddress,dstPort);
socket = new Socket();
socket.setTcpNoDelay(true);
socket.setSoTimeout(5000);
socket.connect(socketAddress, 50000);
// socket = new Socket(dstAddress, dstPort);
System.setProperty("http.keepAlive", "false");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(loc);
///inputStream = new ObjectInputStream(socket.getInputStream());
InputStream is = socket.getInputStream();
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
out.println("");
//response = br.readLine();
try{
while((s=br.readLine())!=null){
red=red+s;
Log.i("server", ""+red);
}
Log.i("server", ""+red);
}catch(Exception ex){
ex.printStackTrace();
}
Log.i("Server response ", "hi"+s);
try {
System.out.println("Read back from server: " + response);
}
catch(Exception e) {
Log.i("Server response ", response+e);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
dataOutputStream.flush();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
res=response;
Log.i("response:", "res"+res);
// Toast.makeText(getApplicationContext(), "hi"+res, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
call this method to send request and get response on your desired place
public void sendtoserver(String msg){
if(isConnectingToInternet()){
servermsg="$loc"+","+ieminumber+","+formattedDate2+","+formattedDate1+","+formattedDate2+","+formattedDate1+","+1+","+lat1+","+"N"+","+lon1+"*";
//10.0.2.2:8081/echo
MyClientTask myClientTask = new MyClientTask(
"10.0.2.2",8081,msg);
myClientTask.execute();
}
}
If you run your app on an emulator and your server runs on the same pc as the emulator then the only way your client app can reach that server is using ip 10.0.2.2 as Google implemented it that way. Meanwhile your computer can have local ip like 192.168.1.12 but your app can not use that. Also the server on the pc is reachable as localhost or 127.0.0.1 by clients running on the same pc. Your app does not run on that pc. Your app runs on the emulator.

Android and Arduino socket

I have created a server and client with Android and Arduino but I have a problem. Android reads only one time. Why? this is my code:
Client Android:
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.240");
socket = new Socket(serverAddr, 8888);
if(socket == null)System.out.println("SOCKET NULL");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
msgFromServer = inFromServer.readLine();
System.out.println(msgFromServer);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
System.out.println("STOP SOCKET");
// close socket
}
}
}
}
Arduino Server:
void loop() {
YunClient client = server.accept();
sensorValue = analogRead(sensorPin);
String myString = String(sensorValue);
if (client) {
String command = "none";
command = client.readString();
Serial.println(sensorValue);
client.print(myString+"\n");
}
}
LOGCAT:
07-24 11:44:24.468: D/OpenGLRenderer(19693): Enabling debug mode 0
07-24 11:44:25.363: I/System.out(19693): 121
121 is the value from Arduino. But this is showing only once.
It works only once. I want receive data from the Arduino every second.
Thank you guys!
You need to take the accept out of the loop. otherwise it send a string and wait for another connect from client.
YunClient client = server.accept();
void loop() {
sensorValue = analogRead(sensorPin);
String myString = String(sensorValue);
if (client) {
String command = "none";
command = client.readString();
Serial.println(sensorValue);
client.print(myString+"\n");
}
}
Also, I don't see where the client sends something to the server. Instead of System.out.println should't it be out.println?

Takes several attempts for server to recieve packet

this has been bugging me for a while and I'm not too sure how I can go about solving this issue.
The issue I am having is it will take several attempts of pushing a packet before the server will actually receive the packet
This is the code I have on the client (Server is Identical but the Send/Receive are reversed) and the Server gets the client IP from the packet to send a return packet
class MainTask extends AsyncTask<Void, Void, Void> {
ProgressDialog progress = null;
Context context = null;
public MainTask(ProgressDialog progress, Context context) {
this.progress = progress;
this.context = context;
}
public void onPreExecute() {
progress.show();
}
public Void doInBackground(Void... unused) {
// Send UDP Packet
String messageStr="Hello Android!";
int server_port = 12441;
DatagramSocket s = null;
DatagramPacket p = null;
InetAddress local = null;
Log.i("EyeceBoxService", "Sending packet");
try {
s = new DatagramSocket();
local = InetAddress.getByName("192.168.0.4");
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
p = new DatagramPacket(message, msg_length,local,server_port);
s.send(p);
Log.i("EyeceBoxService", "Packet Sent!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Receive UDP Packet
byte[] message = new byte[1500];
try {
//progress.setMessage("Retrieving Discovery Information...");
p = new DatagramPacket(message, message.length);
s = new DatagramSocket(server_port);
Log.i("EyeceBoxService", "Waiting for packet");
s.receive(p);
String address = p.getAddress().toString();
Log.i("EyeceBoxService", "Server IP address" + address);
//progress.setMessage("Done...");
//MainActivity.buildNotification(context, address);
progress.dismiss();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void onPostExecute(Void unused) {
}
}
Try to isolate whether the issue is in the server hardware, client hardware, Android framework, network, router config or your code. Try using some debugging tools like wireshark, netcat, ipsend and see what packets are actually sent, received, if packet sending works through commandline, etc.

Categories

Resources