Simple Client Server Application android - android

Hello I am trying to write simple client-server application in android.Here is my code for the client.
package com.sudarshan.client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity 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_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.menu, menu);
return true;
}
}
Here is the code for server
package com.sudarshan.server;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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");
}
}
}
}
The server code crashes.It gives a error as "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sudarshan.server/com.sudarshan.server.MainActivity}: android.os.NetworkOnMainThreadException".
What am i doing wrong?

Solved.
"android.os.NetworkOnMainThreadException" means that Network related tasks are not to be done on main thread directly ie. Activity Class.So, need to make a thread under main thread then do the work.

Related

Android Programme and Python programme WIFI server communication

I'm creating an an Android Application which connects to Python Server and send UP and DOWN command and a Python code response like: light is ON and Light is Off.
Although I add a button to Android application which sends data to Python and a Python server sends back some string or a function to the Android app which shows up in Android TextView (I need to run a function on Raspberry and get the result back to Android in textView).
enter code here
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
Button btnUp;
Button btnDown;
Button rButton;
EditText txtAddress;
Socket myAppSocket = null;
public static String wifiModuleIp = "";
public static int wifiModulePort = 0;
public static String CMD = "0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnUp = (Button) findViewById(R.id.btnUP);
btnDown = (Button) findViewById(R.id.btnDown);
rButton = (Button) findViewById(R.id.rButton);
txtAddress = (EditText) findViewById(R.id.ipAddress);
btnUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getIPandPort();
CMD = "UP";
Soket_AsyncTask cmd_increase_servo = new Soket_AsyncTask();
cmd_increase_servo.execute();
}
});
btnDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getIPandPort();
CMD = "DOWN";
Soket_AsyncTask cmd_decrease_servo = new Soket_AsyncTask();
cmd_decrease_servo.execute();
}
});
rButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getIPandPort();
CMD = "VIEW";
Socket_Received cmd_received_pi = new Socket_Received();
cmd_received_pi.execute();
}
});
}
public void getIPandPort() {
String iPandPort = txtAddress.getText().toString();
String temp[] = iPandPort.split(":");
wifiModuleIp = temp[0];
wifiModulePort = Integer.valueOf(temp[1]);
//Log.d("MYTEST","IP String" +iPandPort);
//Log.d("MY TEST","IP:"+wifiModuleIp);
// Log.d("MY TEST","PORT"+wifiModulePort);
}
public class Soket_AsyncTask extends AsyncTask<Void, Void, Void> {
Socket socket;
protected Void doInBackground(Void... params) {
try {
InetAddress inetAdress = InetAddress.getByName(MainActivity.wifiModuleIp);
socket = new java.net.Socket(inetAdress, MainActivity.wifiModulePort);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeBytes(CMD);
dataOutputStream.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class Socket_Received extends AsyncTask<String, Void, Void> {
ServerSocket cScoket;
Socket socket;
//public TextView textView;
private DataInputStream in;
#SuppressLint("WrongThread")
protected Void doInBackground(String... params) {
try {
cScoket = new ServerSocket(MainActivity.wifiModulePort);
socket = cScoket.accept();
in = new DataInputStream(socket.getInputStream());
InputStreamReader reader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(reader);
final TextView textView = (TextView)findViewById(R.id.txtView);
textView.setText(br.toString());
socket.close();
in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
My Python code here:
enter code here
import lighton
from socket import *
from time import ctime
import time
lighton.setUP()
ctrCmd = ['UP','DOWN','VIEW']
HOST = ''
PORT = 5555
BUFSIZE = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
tcpCliSock,addr = tcpSerSock.accept()
time.sleep(.05)
data = ''
data = tcpCliSock.recv(BUFSIZE).decode()
if not data:
print("there is no data")
break
if data == ctrCmd[0]:
lighton.ledOn()
if data == ctrCmd[1]:
lighton.ledOff()
if data == ctrCmd[2]:
r="hello world"
tcpCliSock.send(r.encode())
tcpSerSock.close();
My Python light on class code here:
import time
def setUP():
print("Setting up...")
def ledOn():
print("led is on")
def ledOff():
print("led is off")
if __name__ == '__main__':
setup()

How to use sockets to read data from server?

The app has MainActivity(contains an EditText and a Button) and DisplayActivity(contains a single TextView)The user enters a message in the EditText and presses the send button. The message string from the EditText gets sent to the server. Then starts a new intent to DisplayActivity. DisplayActivity will read data from the server with readLine(), and set TextView from the data received from the server.
activity_main.xml has a EditText with id="#+id/message_textView" and Button with id="#+id/send_button". DisplayActivity has android:id="#+id/displayTextView".
My code to send data to the server works, but when I try to read data from the server, readline() just stops there and sits there forever.
Android app has MainActivity and DisplayActivity class.
I run the server code in eclipse.
Server code.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.net.*;
import java.io.*;
public class MyServer {
public static void main(String[] args) throws IOException {
int portNumber = 4442;
System.out.println("Starting server..");
try {
while(true) {
ServerSocket serverSocket =
new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String message = in.readLine();
System.out.println(message);//Just print to console, to test if server got message
out.println(message);
serverSocket.close();
clientSocket.close();
// out.close();
// in.close();
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
MainActivity
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
static Socket client;
private PrintWriter printWriter;
private EditText messageET;
private Button sendButton;
private String message;
static String hostIP = "10.0.2.2";
static int port = 4442;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageET = findViewById(R.id.message_textView);
sendButton = findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = messageET.getText().toString();
messageET.setText("");
MyTask myTask = new MyTask();
myTask.execute();
Intent intent = new Intent(getApplicationContext(), DisplayActivity.class);
startActivity(intent);
}
});
}
class MyTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... strings) {
try
{
client = new Socket(hostIP, port);
printWriter = new PrintWriter(client.getOutputStream(), true);
//printWriter.write(message);
printWriter.println(message);
//printWriter.flush();
printWriter.close();
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
return null;
}
}
}
DisplayActivity
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class DisplayActivity extends AppCompatActivity {
//final String TAG = "displayactivitylog";
private Socket socket;
private BufferedReader bufferedReader;
private TextView displayTV;
private String msgReceived = null;
String hostIP = "10.0.2.2";
int port = 4442;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
displayTV = findViewById(R.id.displayTextView);
ReadTask readTask = new ReadTask();
readTask.execute();
}
class ReadTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... strings) {
String result = "";
try
{
//create a new socket and attempt to read from it
socket = new Socket(hostIP,port);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//*****the app stops on this line, and nothing happens after*****
msgReceived = bufferedReader.readLine();
//************************************
// while((msgReceived = bufferedReader.readLine()) != null){
// result += msgReceived;
// }
bufferedReader.close();
socket.close();
}catch(IOException e)
{
e.printStackTrace();
}
return result;
}
//update the TextView with the message from the server
#Override
protected void onPostExecute(String s) {
displayTV.setText(s);
super.onPostExecute(s);
}
}
}
When i run debugger, it literally just stops in DisplayActivity.java on msgReceived = bufferedReader.readLine() in the doInBackground() method and gives no error.
My server starts fine and when I send data from my app to the server, on eclipse it prints out what was sent(and sometimes null for some reason).
---------------SOLUTION---------------
Question was answered by green apps, but basically the server class expects to read something when a connection first opens, and then send out data. However in ReadTask, all it does is try to read data from the server(but it should send data first, then read from it)
Updated code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText messageET;
private Button sendButton;
static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageET = findViewById(R.id.message_textView);
sendButton = findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = messageET.getText().toString();
messageET.setText("");
Intent intent = new Intent(getApplicationContext(), DisplayActivity.class);
startActivity(intent);
}
});
}
}
DisplayActivity.java
public class DisplayActivity extends AppCompatActivity {
private Socket socket;
private PrintWriter printWriter;
private BufferedReader bufferedReader;
private TextView displayTV;
private String msgReceived = null;
String hostIP = "10.0.2.2";
int port = 4442;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
displayTV = findViewById(R.id.displayTextView);
ReadTask readTask = new ReadTask();
readTask.execute();
}
class ReadTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... strings) {
String result = "";
try
{
//create a new socket and attempt to write to it first then read from it
socket = new Socket(hostIP,port);
//add data to the server
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(MainActivity.message);
//get a stream, to be able to read data from the server
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msgReceived = bufferedReader.readLine();
displayTV.setText(msgReceived);
//close the socket connections
printWriter.close();
bufferedReader.close();
socket.close();
}catch(IOException e)
{
e.printStackTrace();
}
return result;
}
}
}
You have two clientsocketss. And two serversockets.
Which is a very strange approach.
The first client sends a line and closes the connection. This works ok as the server tries to read that line and does. Both then close.
Then you start the second client. This one connects to a new serversocket. But this client directly tries to read a line. As the server also tries to read a line from this new client both will wait for eternity on readLine().

AsyncTask unfortunately stops on second execution

I'm trying to get strings from my Arduino with my Android phone, everything goes well except for when I press my updatebutton the second time, it unfortunately stops.
I can't seem to track the problem and I ran out of options so I'm asking for help to you guys now.
package com.TRY.udp2;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private String rcvStr, serverIP="192.168.0.15";
private TextView textLog;//Log for outputs
private EditText textMsg;
Button updateButton;//(dis)connect Button
Boolean connected=false;//stores the connectionstatus
DataOutputStream dataOutputStream = null;//outputstream to send commands
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button updateButton = (Button) findViewById(R.id.updateButton);
textMsg = (EditText) findViewById(R.id.textMsg);
textLog = (TextView) findViewById(R.id.textLog);
updateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String textlogMsg = textMsg.getText().toString();
new synchTask().execute(textlogMsg);
}
});
}
private class synchTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String msg=params[0].toString();
InetAddress toAddress = null;
try
{
toAddress = InetAddress.getByName(serverIP);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
int port=5000;
DatagramSocket dtSocket = null;
try
{
dtSocket = new DatagramSocket(port);
}
catch (SocketException e1)
{
e1.printStackTrace();
}
byte[] dataBytes = msg.getBytes();
DatagramPacket sndPacket = new DatagramPacket(dataBytes, dataBytes.length, toAddress, port);
try
{
dtSocket.send(sndPacket);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
byte[] rcvData = new byte[1024];
DatagramPacket rcvPacket = new DatagramPacket(rcvData, rcvData.length);
dtSocket.receive(rcvPacket);
rcvStr = new String(rcvPacket.getData());
}
catch (IOException e)
{
e.printStackTrace();
}
return rcvStr;
}
protected void onPostExecute(String result) {
textLog.setText(rcvStr);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and if there's a better way of getting strings from arduino please help out.
You probably need to close dtSocket at the end of doInBackground(). Otherwise you will try to create a socket on a bound port when you execute it the second time.

HttpResponse.execute() throws exception

I'm trying to develop a simple app that gets data from web service and displays it
It throws exception exactly when he calls response.execute(client)
package com.example.webbasedapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class GETMethods {
public String getInternetData() throws Exception{
BufferedReader in=null;
String Data=null;
try{
HttpClient client=new DefaultHttpClient();
URI web=new URI("http://www.mybringback.com/");
HttpGet request = new HttpGet();
request.setURI(web);
HttpResponse reponse=client.execute(request);
Log.v("response code", reponse.getStatusLine()
.getStatusCode() + "");
InputStream inp=reponse.getEntity().getContent();
in=new BufferedReader(new InputStreamReader(inp));
StringBuffer buf=new StringBuffer();
String l="";
String nl=System.getProperty("line.separator");
while((l=in.readLine())!=null){
buf.append(l+nl);
}
in.close();
Data=buf.toString();
return Data;
}finally{
if(in!=null){
try{
in.close();
return Data;
}catch (Exception e){
Log.d("error",e.toString());
}
}
}
}
}
And this is my main activity
package com.example.webbasedapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class Home extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
TextView test = (TextView) findViewById(R.id.data);
GETMethods data = new GETMethods();
String d = null;
try {
d = data.getInternetData();
// test.setText(d);
} catch (Exception e) {
// TODO Auto-generated catch block
d = "bla";
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
// Log.d("testW",e.getMessage());
}
test.setText(d);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
You are attempting to access the network on the UI thread which is not allowed due to potential hangup issues. Look into AysncTask and implement GETMethods as one of them. It will look something like this:
public class GETMethods extends AsyncTask<String, Void, String>{
protected void doInBackground(String... params){
YourNetworkCode
}
}

Android Socket Fails

Heres my Server Code
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Threading;
public class SynchronousSocketListener
{
private const int portNum = 4444;
private static ArrayList ClientSockets;
private static bool ContinueReclaim = true;
private static Thread ThreadReclaim;
public static void StartListening()
{
ClientSockets = new ArrayList();
ThreadReclaim = new Thread(new ThreadStart(Reclaim));
ThreadReclaim.Start();
TcpListener listener = new TcpListener(portNum);
try
{
listener.Start();
int TestingCycle = 3;
int ClientNbr = 0;
// Start listening for connections.
Console.WriteLine("Waiting for a connection...");
while (TestingCycle > 0)
{
TcpClient handler = listener.AcceptTcpClient();
if (handler != null)
{
Console.WriteLine("Client#{0} accepted!", ++ClientNbr);
// An incoming connection needs to be processed.
lock (ClientSockets.SyncRoot)
{
int i = ClientSockets.Add(new ClientHandler(handler));
((ClientHandler)ClientSockets[i]).Start();
Console.WriteLine("Added sock {0}", i);
}
--TestingCycle;
}
else
break;
}
listener.Stop();
ContinueReclaim = false;
ThreadReclaim.Join();
foreach (Object Client in ClientSockets)
{
((ClientHandler)Client).Stop();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
private static void Reclaim()
{
while (ContinueReclaim)
{
lock (ClientSockets.SyncRoot)
{
for (int x = ClientSockets.Count - 1; x >= 0; x--)
{
Object Client = ClientSockets[x];
if (!((ClientHandler)Client).Alive)
{
ClientSockets.Remove(Client);
Console.WriteLine("A client left");
}
}
}
Thread.Sleep(200);
}
}
public static int Main(String[] args)
{
while (true)
{
StartListening();
}
return 0;
}
}
class ClientHandler
{
TcpClient ClientSocket;
bool ContinueProcess = false;
Thread ClientThread;
public ClientHandler(TcpClient ClientSocket)
{
this.ClientSocket = ClientSocket;
}
public void Start()
{
ContinueProcess = true;
ClientThread = new Thread(new ThreadStart(Process));
ClientThread.Start();
}
private void Process()
{
// Incoming data from the client.
string data = null;
// Data buffer for incoming data.
byte[] bytes;
if (ClientSocket != null)
{
NetworkStream networkStream = ClientSocket.GetStream();
ClientSocket.ReceiveTimeout = 100; // 1000 miliseconds
while (ContinueProcess)
{
bytes = new byte[ClientSocket.ReceiveBufferSize];
try
{
int BytesRead = networkStream.Read(bytes, 0, (int)ClientSocket.ReceiveBufferSize);
//BytesRead--;
if (BytesRead > 0)
{
Console.WriteLine("Bytes Read - Debugger " + BytesRead);
data = Encoding.ASCII.GetString(bytes, 0, BytesRead);
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] sendBytes = Encoding.ASCII.GetBytes("I rec ya abbas");
networkStream.Write(sendBytes, 0, sendBytes.Length);
if (data == "quit") break;
}
}
catch (IOException) { } // Timeout
catch (SocketException)
{
Console.WriteLine("Conection is broken!");
break;
}
Thread.Sleep(200);
} // while ( ContinueProcess )
networkStream.Close();
ClientSocket.Close();
}
} // Process()
public void Stop()
{
ContinueProcess = false;
if (ClientThread != null && ClientThread.IsAlive)
ClientThread.Join();
}
public bool Alive
{
get
{
return (ClientThread != null && ClientThread.IsAlive);
}
}
} // class ClientHandler
Heres my Client Code:
package com.example.socketclient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class SocketCode extends Activity {
public TextView txt;
protected SocketCore Conn;
public Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_code);
b = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
Conn = new SocketCore(this,txt);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Conn.execute();
}
});
}
}
SocketCore
package com.example.socketclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
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.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
class SocketCore extends AsyncTask<Context, Integer, String>
{
String text = "";
String finalText = "";
private Context ctx;
ProgressDialog dialog;
TextView Msg;
Socket socket;
public SocketCore(Context applicationContext,TextView Change)
{
// TODO Auto-generated constructor stub
ctx = applicationContext;
dialog = new ProgressDialog(applicationContext);
Msg = Change;
}
#Override
protected String doInBackground(Context... arg0) {
// TODO Auto-generated method stub
try {
InetAddress serverAddr = InetAddress.getByName("192.168.0.150");
Log.d("TCP", "C: Connecting....");
socket = new Socket(serverAddr,4444);
// Log.d("TCP", "C: I dunno ...");
String message = "Hello Server .. This is the android client talking to you .. First we are testing Server Crashing";
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//serverReturnString = System.Text.Encoding.ASCII.GetString(response, 0, bytes);
out.println("quit");
//out.print("h");
while ((text = in.readLine()) != null) {
finalText += text;
if(text=="quit")
{
socket.close();
}
Log.d("TCP", "C: Done."+finalText);
}
// Msg.setText("LOLZ");
Log.d("TCP", "C: Sent.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} /*finally {
socket.close();
Log.d("TCP", "S: Closed");
} */
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
//dialog.setMessage("Recieved: "+finalText);
return "COMPLETE";
}
protected void onPostExecute(String x)
{
super.onPostExecute("Finished");
dialog.dismiss();
Msg.setText(finalText);
}
protected void onPreExecute()
{dialog.setTitle("Initializing Connection");
dialog.setMessage("Connecting");
dialog.show();
}
}
Server can read from android phone also the android client get message from server.
The Problem is whenever The Server detects connection and start Receives text and Sends Reply . The code doesnt accept more connection after that .
Note:
I tried to to test using C# client it works fine so i got a problem on the client side
You can't use more then AsyncTask.
The simplest approach is to move the code inside doInBackground() to a Runnable and then start a new Thread with that runnable on every click.
Example:
private Runnable rSocketCore = new Runnable() {
public void run() {
//here goes your connection code
}
};
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread(rSocketCore).start();
}
Note: You will also need an Handler if you want to communicate from the thread to the UI.
Regards.

Categories

Resources