How to send data(string) server-to client with button?
I made several attempts, but I'm new to android programming. Therefore
waiting for your help..my expectations: just a small sample..
My goal is to send data from server to client.
enter code here public class MainActivity extends ActionBarActivity {
private TextView tvClientMsg,tvServerIP,tvServerPort;
private final int SERVER_PORT = 13003; //Define the server port
#Override
protected void onCreate(Bundle saveenter code heredInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvClientMsg = (TextView) findViewById(R.id.textViewClientMessage);
tvServerIP = (TextView) findViewById(R.id.textViewServerIP);
tvServerPort = (TextView) findViewById(R.id.textViewServerPort);
tvServerPort.setText(Integer.toString(SERVER_PORT));
getDeviceIpAddress();
new Thread(new Runnable() {
#Override
public void run() {
try {
ServerSocket socServer = new ServerSocket(SERVER_PORT);
Socket socClient = null;
while (true) {
socClient = socServer.accept();
ServerAsyncTask serverAsyncTask = new ServerAsyncTask();
serverAsyncTask.execute(new Socket[] {socClient});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void getDeviceIpAddress() {
try {
for (Enumeration<NetworkInterface> enumeration = NetworkInterface
.getNetworkInterfaces(); enumeration.hasMoreElements();) {
NetworkInterface networkInterface = enumeration.nextElement();
for (Enumeration<InetAddress> enumerationIpAddr = networkInterface.getInetAddresses(); enumerationIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumerationIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress.getAddress().length == 4) {
tvServerIP.setText(inetAddress.getHostAddress());
}
}
}
} catch (SocketException e) {
Log.e("ERROR:", e.toString());
}
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class ServerAsyncTask extends AsyncTask<Socket, Void, String> {
protected String doInBackground(Socket... params) {
String result = null;
Socket mySocket = params[0];
try {
InputStream is = mySocket.getInputStream();
PrintWriter out = new PrintWriter(
mySocket.getOutputStream(), true);
out.println("Hello from server");
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
result = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String s) {
tvClientMsg.setText(s);
}
}
}
Related
I need to create an application using android socket level programming, I created a connection between server and client but I need to show waiting server IP list at client side and select one IP from the list and establish a connection between them.
Here is my code for server side
public class Server extends AppCompatActivity {
private static final String TAG = "ServerActivity";
private TextView tvServerStatus;
private TextView recievemsg;
InetAddress receiverAddress;
public static String SERVERIP = "";
DatagramSocket datagramSocket;
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
Handler updateConversationHandler;
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
updateConversationHandler = new Handler();
tvServerStatus = (TextView) findViewById(R.id.tvServerStatus);
recievemsg=(TextView)findViewById(R.id.send_msg);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = "0123456789".getBytes();
byte[] address=SERVERIP.getBytes();
receiverAddress = InetAddress.getByAddress(address);
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, receiverAddress, 8080);
datagramSocket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getLocalIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public class ServerThread implements Runnable {
#Override
public void run() {
try {
Log.e(TAG, "Server IP: " + SERVERIP);
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Listening On Ip: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (!Thread.currentThread().isInterrupted()) {
{
try {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(client);
new Thread(commThread).start();
// Log.e(TAG, "Client Socket: " + client);
// new Clients_Handle(client, ROOT_DIRECTORY).start();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Error");
}
});
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() {
recievemsg.setText(recievemsg.getText().toString() + "Client Says: " + msg + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
Log.e(TAG,"Socket Closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is my client side code
public class Clientss extends AppCompatActivity {
private static final String TAG = "Client_Activity";
private EditText etServerIp;
private EditText etMsg;
private Button btnConnectClients;
private Button btnSendMsg;
private TextView textIn;
private String serverIpAddress = "";
private String t;
private boolean connected = false;
DatagramSocket datagramSocket;
DatagramPacket packet;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clientss);
Log.e(TAG, "ONCREATE METHOD");
textIn = (TextView)findViewById(R.id.txt_msg);
initializations();
eventClickListener();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = new byte[10];
packet = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(packet);
byte[] buff = packet.getData();
textIn.setText(buff.toString());
System.out.println("this is incoming ip"+buff.toString());
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// textIn.setText(t);
}
private void eventClickListener() {
btnConnectClients.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = etServerIp.getText().toString().trim();
connectsClient();
}
}
});
btnSendMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = etMsg.getText().toString().trim();
ClientResponseTask clientResponseTask=new ClientResponseTask(msg);
clientResponseTask.execute();
}
});
}
private void connectsClient() {
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
private void initializations() {
etServerIp = (EditText) findViewById(R.id.etServerIp);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSendMsg = (Button) findViewById(R.id.btnMsgSend);
btnConnectClients = (Button) findViewById(R.id.btnConnect);
}
private class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.e(TAG, "C: Connecting...");
socket = new Socket(serverAddr, Server.SERVERPORT);
System.out.println("this is socket"+socket);
connected = true;
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
//showToast("");
Log.e(TAG, "C: Connected..." + socket);
} catch (Exception e) {
Log.e(TAG, "C: Error", e);
connected = false;
}
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.arg1 == 1)
Toast.makeText(getApplicationContext(),"Connected...", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onDestroy() {
if (socket != null) try {
socket.close();
Log.e(TAG, "C: Socket Closed.");
} catch (IOException e) {
e.printStackTrace();
} finally
{
try
{
socket.close();
}
catch(Exception e){}
}
super.onDestroy();
}
protected class ClientResponseTask extends AsyncTask<Void,Void,Void> {
String msg;
ClientResponseTask(String msg){
this.msg=msg;
}
#Override
protected Void doInBackground(Void... params) {
if (connected) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(msg);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
else {
connectsClient();
}
return null;
}
}
}
Please help me to find a solution.
I wrote a server for android. The Server works good and I succeed to send a message from app that simulate a client (SocketTest).
So I wrote a client in C# by my self.
I tried my client against SocketTest(As server of course) and it's work.
The connection step to android seems to be good, I get no exception.
But I don't see the message in my Android device.
C# code
{
public partial class sendSms : Form
{
TcpClient client;
NetworkStream ns;
public sendSms()
{
InitializeComponent();
}
private void Connect()
{
client = new TcpClient("192.168.14.76", 8080);
//client = new TcpClient("127.0.0.1", 8080);
ns = client.GetStream();
}
private void button1_Click(object sender, EventArgs e)
{
Connect();
}
private void sendBtn_Click(object sender, EventArgs e)
{
SendMessage();
}
private void SendMessage()
{
string sendMSG = msgTB.Text;
ns.Write(Encoding.UTF8.GetBytes(sendMSG), 0, sendMSG.Length);
ns.Flush();
}
}
}
Andorid Server
public class MainActivity extends AppCompatActivity {
private ServerSocket serverSocket;
Handler UiHandler;
Thread thread = null;
private TextView textView;
private static final int PORT = 8080;
private String status = null;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textView = (TextView) findViewById(R.id.ipTextView);
UiHandler = new Handler();
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
String ipAddress = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
textView.setText("Ip - " + ipAddress + ", Port - " + PORT);
// statusTxt.setText("Hello");
this.thread = new Thread(new ServerThread());
this.thread.start();
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(PORT);
} 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();
UiHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String[] getPhoneAndMSG(String msg)
{
return msg.split("&");
}
class updateUIThread implements Runnable
{
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
try {
textView.setText(msg);
String[] numAndMsG = getPhoneAndMSG(msg);
// SmsManager smsManager = SmsManager.getDefault();
// Toast.makeText(getApplicationContext(), numAndMsG[0] +" " +numAndMsG[1] , Toast.LENGTH_LONG).show();
// smsManager.sendTextMessage(numAndMsG[0], null, numAndMsG[1], null, null);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS Faild", Toast.LENGTH_LONG).show();
}
// textView.setText(textView.getText().toString()+"Client Says: "+ msg + "\n");
}
}
#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_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Problem solved!
string sendMSG = msgTB.Text + "\r\n";
On the MainActivity.java I have a method that connect with a server:
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
I'm calling this method from onTouchEvent():
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
circlePath.addCircle(eventX, eventY, 50, Path.Direction.CW);
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (is_start == true)
{
response = Get("http://10.0.0.2:8098/?cmd=start");
is_start = false;
}
else
{
response = Get("http://10.0.0.2:8098/?cmd=stop");
is_start = true;
}
if (response!=null)
{
String a = null;
try
{
a = new String(response,"UTF-8");
textforthespeacch = a;
MainActivity.currentActivity.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
circlePath.reset();
break;
default:
return false;
}
invalidate();
return true;
}
So now i'm connecting all the time to 10.0.0.2:8098
But that's when i connect my android device on my network on my pc room.
But if i move to the living room and connect to the network there a differenet network with another pc the pc ip is differenet in this case: 10.0.0.3:8099
So i added a button click event to the MainActivity.java:
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
currentActivity = this;
initTTS();
}
public void addListenerOnButton() {
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
}
});
}
Inside the button click event I want to check after connected to the network with a wifi if the pc ip is 10.0.0.3:8099 or 10.0.0.2:8098
I need that it will try to connect to this servers and if success then to set to a global variable global string the ip.
I added a global variable: string ipaddress
Now i use static address in my code but i need to check which ip address is correct and then to set this ip to the variable which i will use later in my code as the ip address.
How do I make the checking in the button click event ?
This is what i tried now:
At the top of my MainActivity i added:
private final String[] ipaddresses = new String[2];
private final Integer[] ipports = new Integer[2];
Socket socket = null;
Then in the onCreate:
ipaddresses[0] = "10.0.0.3";
ipaddresses[1] = "10.0.0.2";
ipports[0] = 8098;
ipports[1] = 8088;
addListenerOnButton();
new Thread(new ClientThread()).start();
Then
public void addListenerOnButton() {
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
try {
String str = btnClick.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And the ClientThread
class ClientThread implements Runnable {
#Override
public void run() {
for (int i=0; i<ipaddresses.length; i++)
{
try
{
InetAddress serverAddr = InetAddress.getByName(ipaddresses[i]);
socket = new Socket(serverAddr, ipports[i]);
} catch (UnknownHostException e1)
{
e1.printStackTrace();
} catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
This is a screenshot of the exception message i'm getting:
The exception is on the line:
new OutputStreamWriter(socket.getOutputStream())),
You must open sockets to check server connectivity. Here is an example on you send strings to server on click event:
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 8099;
private static final String SERVER_IP = "10.0.0.3";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
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);
} 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();
}
}
}
}
So if you get an exception trying to connect to server, it means you haven't connectivity.
I am trying to establish a socket connection between two different devices at different places. I am using Airtel SIM on my android device. I am running following code on the device:
public class MainActivity extends Activity
{
Context context;
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
Sql s = new Sql(context);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
new GetPublicIPTask().execute();
}
private class SocketServerThread extends Thread
{
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run()
{
try
{
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
info.setText("Port: " + serverSocket.getLocalPort());
}
});
while (true)
{
Socket socket = null;
try
{
socket = serverSocket.accept();
}
catch (Exception e)
{
e.printStackTrace();
}
count++;
message += "#" + count + " from " + socket.getInetAddress() + ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread
{
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c)
{
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run()
{
OutputStream outputStream;
String msgReply = "Hello client " + cnt;
try
{
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replied: " + msgReply + "\n";
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText(message);
}
});
}
catch (IOException e)
{
e.printStackTrace();
message += "Exception! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText(message);
}
});
}
}
public class GetPublicIPTask extends AsyncTask<String, Integer, String>
{
ProgressDialog progressDialog;
String serverResponse = "";
public GetPublicIPTask()
{
progressDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute()
{
if (!NetWorkInfo.isOnline(context))
{
Toast.makeText(context, "No Internet Connection", Toast.LENGTH_LONG).show();
return;
}
progressDialog.setMessage("Getting IP");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... sUrl)
{
BufferedReader in = null;
int TIME_OUT = 1000 * 60 * 10;
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
HttpConnectionParams.setSoTimeout(params, TIME_OUT);
HttpGet httppost = new HttpGet("http://checkip.dyndns.org");
httppost.setHeader("Content-Type", "application/json");
try
{
HttpResponse response = httpclient.execute(httppost);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null)
{
sb.append(line);
}
serverResponse = sb.toString();
return serverResponse;
}
catch (Exception ex)
{
Log.d("Socket Server", "StackTrace : " + ex.getStackTrace().toString());
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
return null;
}
#Override
protected void onPostExecute(String result)
{
if (progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
infoip.setText(serverResponse);
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
super.onPostExecute(result);
}
}
}
And from terminal I am hitting the mobile app:
telnet publicIpAddress 8080
Same process working in local network, but not working in mobile networks.
Hi I am making a chat application however when I try to update the view with the received string I get an CalledFromWrongThreadException, however it worked earlier, and my understanding of the handler is that it is created exactly for calls from another thread.
public class ChatActivity extends ActionBarActivity {
ServerSocket serverSocket;
Thread listenThread;
Thread sendThread;
Socket socket = null;
String strIP = "";
volatile String error;
final static int port = 6000;
TextView chatView;
TextView errorView;
volatile static String rcv = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
if (socket == null) {
try {
this.listenThread = new Thread(new Listener());
this.listenThread.start();
} catch (Exception e) {
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chat, 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();
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.action_connectIP) {
Intent intent = new Intent(this, ConnectActivity.class);
startActivityForResult(intent, 1);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) {
if (requestCode == 1) {
if (data.hasExtra("IP"))
strIP = data.getExtras().getString("IP");
Toast.makeText(this, strIP, Toast.LENGTH_LONG).show();
// luk for at forhindre flere i at forbinde
try {
serverSocket.close();
} catch (IOException e) {
error = e.toString();
Message message = new Message();
message.what = -1;
UpdateHandler.sendMessage(message); }
}
}
}
#Override
protected void onStop() {
super.onStop();
if (listenThread != null)
if (listenThread.isAlive())
try {
serverSocket.close();
} catch (IOException e) {
error = e.toString();
Message message = new Message();
message.what = -1;
UpdateHandler.sendMessage(message);
}
listenThread.interrupt();
if (sendThread != null)
if (sendThread.isAlive())
sendThread.interrupt();
}
Handler UpdateHandler = new Handler() {
public void handleMessage(Message msg) {
this.obtainMessage();
switch (msg.toString()) {
case "0":
// TODO: afbryd forbindelsen
break;
case "-1":
insertError();
break;
default:
InsertChat();
}
}
};
void ThreadHandler() {
}
void InsertChat() {
if(chatView != null)
chatView.setText(rcv);
else
{
chatView = (TextView) findViewById(R.id.txtViewChat);
chatView.setText(rcv);
}
}
void insertError()
{
errorView = (TextView) findViewById(R.id.viewFejl);
errorView.setText(error);
}
public void SendChat(View view) {
// gør det hele asynkront og send beskeder i en tråd for sig.
if(sendThread == null)
sendThread = new Thread(new SendMessage());
if (!sendThread.isAlive()) {
this.sendThread = new Thread(new SendMessage());
this.sendThread.start();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_chat, container,
false);
return rootView;
}
}
class Listener implements Runnable {
boolean shouldRun = true;
#Override
public void run() {
Looper.prepare();
// Looper.loop();
BufferedReader reader = null;
if (socket == null) {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
Message message = new Message();
rcv = "debug1";
UpdateHandler.sendMessage(message);
try {
if(strIP != "")
socket = new Socket(strIP, port);
else if (socket == null)
socket = serverSocket.accept();
Toast.makeText( getApplicationContext(), socket.getInetAddress().toString()+ " er forbundet", Toast.LENGTH_LONG).show();
while (!Thread.currentThread().isInterrupted() && shouldRun) {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
rcv = reader.readLine();
if(rcv == null) //er forbindelsen forsvundet?
shouldRun = false;
else
{
message.what = 0;
UpdateHandler.dispatchMessage(Message.obtain());
}
}
} catch (Exception e) {
error = e.toString();
message.what = -1;
UpdateHandler.dispatchMessage(message);
if(e != null)
e.printStackTrace();
}
try {
if (reader != null)
{
reader.close();
socket.close();
socket = null;
serverSocket.close();
}
} catch (IOException e) {
error = e.toString();
message.what = -1;
UpdateHandler.dispatchMessage(message);
if(e != null)
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), "lukker", Toast.LENGTH_LONG).show();
}
}
class SendMessage implements Runnable {
#Override
public void run() {
Looper.prepare();
try {
EditText textBox = (EditText) findViewById(R.id.txtChat);
PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
writer.println(textBox.getText().toString());
writer.flush(); //send før bufferen er fuld
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "fejl", Toast.LENGTH_LONG).show();
}
}
}
}
I can't figure out how else to update the UI since you can't run sockets on the UI thread.