Android Socket Fails - android

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.

Related

Android Client sends Objects to server and server does receive them but client can't read response

I am sending a Collection(NetworkObject) via ObjectInput and Outputstreams to a server and he receives them without a problem, but he can't read the response which should be a string(also object now for testing). But the app keeps telling me the socket is closed.
Thanks in advance.
My whole Activity
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import com.example.cl.BasicActivity;
import com.example.cl.data.NetworkObject;
import com.example.cl.R;
import com.example.cl.data.Produkt;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import static java.lang.Thread.sleep;
public class ServerHandler extends BasicActivity implements View.OnClickListener {
public static final int SERVERPORT = 26000;
public static final String SERVER_IP = "192.168.1.2";
//public static final String SERVER_IP = "192.168.0.206";
private ClientThread clientThread;
private Thread thread;
private LinearLayout msgList;
private Handler handler;
private int clientTextColor;
private EditText edMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
setTitle("Client");
clientTextColor = ContextCompat.getColor(this, R.color.green);
handler = new Handler();
msgList = findViewById(R.id.msgList);
edMessage = findViewById(R.id.edMessage);
}
public TextView createLine(String message, int color) {
if (null == message || message.trim().isEmpty()) {
message = "<Empty Message>";
}
TextView tv = new TextView(this);
tv.setTextColor(color);
tv.setText(message );
tv.setTextSize(20);
tv.setPadding(0, 5, 0, 0);
return tv;
}
public void showMessage(final String message, final int color) {
handler.post(new Runnable() {
#Override
public void run() {
msgList.addView(createLine(message, color));
}
});
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.connect_server) {
msgList.removeAllViews();
showMessage("Connecting to Server...", clientTextColor);
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
return;
}
if (view.getId() == R.id.send_data) {
String clientMessage = edMessage.getText().toString().trim();
showMessage(clientMessage, Color.BLUE);
if (null != clientThread) {
clientThread.sendMessage(clientMessage);
}
}
if (view.getId() == R.id.send_elem) {
if (null != clientThread) {
clientThread.sendElem(/*bestellung*/);
}
}
}
class ClientThread implements Runnable {
private Socket socket;
//private BufferedReader input;
private ObjectInputStream ois;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
//sleep(250);
if (socket != null)
showMessage("Connected to Server!", clientTextColor);
while (!Thread.currentThread().isInterrupted()) {
//this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
//ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
//String message = input.readLine();
NetworkObject networkObject = (NetworkObject) ois.readObject();
/*
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
showMessage(message, Color.RED);
break;
}
*/
showMessage("Server: " + networkObject, clientTextColor);
// showMessage("Server: " + message, clientTextColor);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException | ClassNotFoundException e1) {
e1.printStackTrace();
}
}
void sendMessage(final String message) {
new Thread(new Runnable() {
#Override
public void run() {
try(ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));) {
if (null != socket) {
oos.writeUTF(message);
oos.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
void sendElem(/*NetworkObject networkObject*/) {
new Thread(new Runnable() {
#Override
public void run() {
try(ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));) {
if (null != socket) {
Produkt produkt = new Produkt("Bier","Zipfer",16,3.50,1,true);
List<Object> produktList = new LinkedList<>();
produktList.add(produkt);
produktList.add(produkt);
NetworkObject networkObject = new NetworkObject("order",46020849,1,produktList);
showMessage(networkObject.toString(), Color.BLUE);
oos.writeObject(networkObject);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
The thread in the Clienthandler which should read it also contains the sending methods but they should work.
private Socket socket;
//private BufferedReader input;
private ObjectInputStream ois;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
//sleep(250);
if (socket != null)
showMessage("Connected to Server!", clientTextColor);
while (!Thread.currentThread().isInterrupted()) {
//this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
//ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
//String message = input.readLine();
NetworkObject networkObject = (NetworkObject) ois.readObject();
/*
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
showMessage(message, Color.RED);
break;
}
*/
showMessage("Server: " + networkObject, clientTextColor);
// showMessage("Server: " + message, clientTextColor);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException | ClassNotFoundException e1) {
e1.printStackTrace();
}
}
The error I get
W/System.err: java.net.SocketException: Socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:119)
at java.net.SocketInputStream.read(SocketInputStream.java:176)
at java.net.SocketInputStream.read(SocketInputStream.java:144)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:248)
W/System.err: at java.io.BufferedInputStream.read1(BufferedInputStream.java:288)
at java.io.BufferedInputStream.read(BufferedInputStream.java:347)
at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2454)
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2470)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2947)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:858)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:353)
at com.example.cl.serverKom.ServerHandler$ClientThread.run(ServerHandler.java:131)
at java.lang.Thread.run(Thread.java:919)

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 get multiple messages from server in android socket

I am implementing socket programming in android. I am successfully getting data from client and displaying it to the server.
The asynctask is as follows:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} 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 {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
The above code gets data from server and write it to the text view. I want to use the same socket to get data multiple times from server, unless a particular button is clicked. But, in doInBackground, we can't use any ui component. I want to change the following component, so that I can recieve multiple data from the server:
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
I tried to use
onProgressUpdate
but it didn't work either. Please help me to solve this.
Edit 1: the client's main activity :
package com.example.shiza.client;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "CLIENT_MESSAGE";
EditText ip_address;
EditText port_number;
EditText message_client;
Button button_send;
Button button_cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void connect(View view) {
// ip_address = (EditText) findViewById(R.id.ip_address);
// ip_address.setText("192.168.9.100");
// port_number = (EditText) findViewById(R.id.port_number);
// port_number.setText("8080");
message_client = (EditText) findViewById(R.id.message_client);
button_send = (Button)findViewById(R.id.button_send);
button_cancel = (Button)findViewById(R.id.button_cancel);
Log.d(TAG, "connecting to the server.");
// new ConnectToServer(ip_address.getText().toString(), port_number.getText().toString(), message_client,button_send,button_cancel).execute();
new ConnectToServer("192.168.9.100","8080", message_client,button_send,button_cancel).execute();
}
}
class ConnectToServer extends AsyncTask<Void, DataOutputStream, Void> {
private static final String TAG = "CLIENT_MESSAGE";
String ip_address;
int port_number;
EditText message_client;
Button button_send;
Button button_cancel;
boolean send = false;
boolean cancel = false;
public ConnectToServer(String ip_address, String port_number, EditText message_client,Button button_send,Button button_cancel) {
this.ip_address = ip_address;
this.port_number = Integer.parseInt(port_number);
this.message_client = message_client;
this.button_cancel = button_cancel;
this.button_send = button_send;
}
#Override
protected Void doInBackground(Void... params) {
try {
Socket socket = new Socket(ip_address, port_number);
if (LoggerConfig.TAG) {
Log.d(TAG, "the socket is created at " + ip_address);
}
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
while (!cancel )
publishProgress(output);
// output.writeUTF("Hello from string");
if (LoggerConfig.TAG) {
Log.d(TAG, "I have written and closed the loop.");
}
socket.close();
} catch (IOException e) {
if (LoggerConfig.TAG) {
Log.d(TAG, "Could not connect.");
}
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(DataOutputStream... values) {
super.onProgressUpdate(values);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
send = true;
}
});
button_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel = true;
}
});
Log.d(TAG, "I am in onProgressUpdate");
if ( send )
{
try {
values[0].writeUTF(message_client.getText().toString());
Log.d(TAG, "I am in onProgressUpdate try.");
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "I am in onProgressUpdate catch.");
}
send = false;
}
}
}
The server's main activity:
package com.example.shiza.server;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
TextView ip_address;
TextView client_message;
TextView server_status;
TextView show_client_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip_address = (TextView) findViewById(R.id.ip_address);
client_message = (TextView) findViewById(R.id.get_client_message);
server_status = (TextView) findViewById(R.id.server_status);
show_client_message = (TextView) findViewById(R.id.show_client_message);
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
ip_address.setText(ip);
// Making a server socket here
}
public void startServer(View view) {
GetFromClient getFromClient = new GetFromClient(this,server_status,show_client_message);
getFromClient.execute();
}
}
class GetFromClient extends AsyncTask<Void, String, Void> {
Context context;
TextView server_status;
TextView show_client_message;
String TAG = "SERVER_MESSAGE";
String inputFromClient = null;
public GetFromClient(Context context,TextView server_status,TextView show_client_message) {
this.context = context;
this.server_status = server_status;
this.show_client_message = show_client_message;
}
#Override
protected Void doInBackground(Void... params) {
Socket socket;
try {
ServerSocket serverSocket = new ServerSocket(8080);
Log.d(TAG, "Server Socket is starting....");
// server_status.setText("The server is running");
publishProgress("okay");
socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
// Calling the second background task for handling input from server
// Log.d(TAG, "Server Socket is started....");
do
{
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
inputFromClient = input.readUTF();
publishProgress(inputFromClient);
}
while ( inputFromClient != "bye" );
// publishProgress(2);
socket.close();
} catch (IOException e) {
Log.d(TAG, "I am in catch.");
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d(TAG, "I am in onProgress update.");
if ( values[0].equals("okay") )
{
server_status.setText("Server has been started");
server_status.setTextColor(context.getResources().getColor(R.color.green));
}
else
{
show_client_message.setText(values[0]);
}
}
protected void onPostExecute(Void inputFromClient)
{
Log.d(TAG, "I am in onPostExecute.");
server_status.setText("Server is not running");
server_status.setTextColor(context.getResources().getColor(R.color.red));
}
}
I am able to do the messaging but the following loop blocks everything:
do
{
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
inputFromClient = input.readUTF();
publishProgress(inputFromClient);
}
while ( inputFromClient != "bye" );
You can update your TextView in the doInBackground method using RunUiThread. After receiving the data from server just call
runOnUiThread(new Runnable() {
#Override
public void run() {
//here you update the views
}
});

Java.lang.IllegalArgumentException: host=null, port=4444

If I run my app in the emulator my app crashes immediately. I get the error 'Caused by: java.lang.IllegalArgumentException: host=null, port=4444.' Logcat says the error comes from InetSocketAdress. This is my server code:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
/**
* Created by Charlie on 26-3-2015.
*/
public class Server extends AsyncTask<Void, Void, String> {
private String message;
private String ip;
public static int port = 4444;
private String serverResponse = null;
public Server(String ip, int port, String message ) {
super();
//IP, Port en bericht om naar server te sturen
this.message = message;
this.ip = ip;
this.port = port;
}
#Override
protected String doInBackground(Void... params) {
try {
Socket serverSocket = new Socket();
serverSocket.connect(new InetSocketAddress(this.ip, this.port), 4444);
this.sendMessage(message, serverSocket);
InputStream input;
try {
input = serverSocket.getInputStream();
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(input));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
}
responseStreamReader.close();
this.serverResponse = stringBuilder.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Response: " + serverResponse);
} catch (UnknownHostException e) {
Log.d("debug", "can't find host");
} catch (SocketTimeoutException e) {
Log.d("debug", "time-out");
} catch (IOException e) {
e.printStackTrace();
}
return serverResponse;
}
private void sendMessage(String message, Socket serverSocket) {
OutputStreamWriter outputStreamWriter = null;
try {
outputStreamWriter = new OutputStreamWriter(serverSocket.getOutputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
if (outputStreamWriter != null) {
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
PrintWriter writer = new PrintWriter(bufferedWriter, true);
writer.println(message);
}
}
}
The code of the class where the user can fill in the IP:
package com.imptmd.charliemacdonald.desleutelaar_v3;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.ExecutionException;
public class GebruikerIP extends Activity {
private Boolean serverCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Slotenbedrijf De Sleutelaar");
//Check voor internet verbinding
if(NetwerkCheck.isInternetAvailable(GebruikerIP.this))
{
}
else
{
Toast.makeText(GebruikerIP.this, "Er is helaas geen internetverbinding geconstateerd, daarom wordt nu de laatst opgehaalde informatie getoond.!", Toast.LENGTH_LONG).show();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gebruikerip);
Button ipButton = (Button) findViewById(R.id.serverbutton);
ipButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
verbindServer();
}
});
//Enter key afvangen
EditText ipInvoer = (EditText) findViewById(R.id.ipinvoeren);
ipInvoer.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_ENTER:
verbindServer();
break;
default:
return false;
}
return true;
}
});
}
//server connectie maken voor ophalen van diensten
public void verbindServer() {
TextView ipVeld = (TextView) findViewById(R.id.ipinvoeren);
String ip = ipVeld.getText().toString();
Log.i("ip", ip);
String response = null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("slotenlijst", "");
} catch (JSONException e) {
e.printStackTrace();
}
try {
try {
response = new Server(ip,
4444, jsonObject.toString()).execute().get();
//exceptions afvangen
} catch (InterruptedException e)
{
}
} catch (ExecutionException e1)
{
}
if (response == null) {
serverCheck = false;
Toast.makeText(this, "Verbinden met server mislukt, staat server aan?", Toast.LENGTH_LONG).show();
} else {
//doorgaan naar MainActivity
serverCheck = true;
HoofdschermFragment.serverIp = ip;
Intent startApp = new Intent(this, MainActivity.class);
startActivity(startApp);
}
}
#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_gebruiker_ip, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
I can't find out how I can fix this error. Help would me appreciated. Thanks!
change it to
InetAddress inetServer = InetAddress.getByName(IP);
than
Socket socket = new Socket(inetServer, devicePort);
and if you are using for Server Socket than use below line
ServerSocket socket = new ServerSocket(devicePort,int backlognumber, inetServer);

Cannot display toast in a catch

package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
ArrayList<String> mNameList = new ArrayList<String>();
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=10&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("carriots.apikey", "1234567");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
return returnMsg;
}
protected void onPostExecute(String result)
{
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
How can I actually display a toast without stoping it? Whenever it falls into the catch it is not responding.
............................................................................................................................................................................................................................................................................
If you are using try-catch in a worker thread and want to display Toast, then I am afraid it is not going to work. You will have to do it in Main(UI) thread.
Try following:
try {
dateTo = dateFormatTo.parse(To);
}
catch (java.text.ParseException e) {
your_activity_context.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
Try following:
In getDateTo():
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
return -1L; // attention here
}
In getData():
long dateTo = -1L;
if((dateTo = getDateTo()) == -1L){
return null;
}
String toTS = "" + getDateTo();
In onPostExecute:
if(result == null) {
return;
}
Make boolean flag = false; globally.
Inside catch block make flag = true;
Run Toast inside an if block like
if (flag) {
Toast.makeText(this, "Sorry, Couldn't find anything!", Toast.LENGTH_LONG).show();
}
inside your onclick method.

Categories

Resources