I have written a small client server application for android. The client is a Java program running on my PC while my Android phone is a server. I'm facing force close issues in my server program. The server starts pretty good, but when I send a string from my PC client, the android application (server) force closes. It has become really annoying. Please help!
Here is my client program running on my PC:
package javaNetPackage;
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 javax.swing.JOptionPane;
public class javaClient {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String serverIpAddress = "10.81.242.220";
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
echoSocket = new Socket(serverAddr, 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to server");
System.exit(1);
}
String str = JOptionPane.showInputDialog("Please give number");
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(echoSocket.getOutputStream())),true);
out.println(str);
out.close();
in.close();
echoSocket.close();
}
}
And here is my server code running on Android:
package com.vinit.androidserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MainActivity extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 4444;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("Nothing from client yet");
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(mClientMsg);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Permissions:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Update:: Okay, I solved the issue of force close. I deleted the permission tags in manifest.xml and re-typed them. But now, I'm facing a different problem here. The sent string from PC client is not getting displayed in my server TextView (textView1 in layout xml, referred to as tv in server code). Default message in tv is "Nothing from client yet". When I send a string from PC client, default message disappears but sent string is not updated in server TextView (tv).
You should set the received string to your Message object sent in myUpdateHandler.sendMessage(m); instead of your mClientMsg field.
You can create and send the Message object as below:
String st = null;
st = input.readLine();
Message msg = Message.obtain(myUpdateHandler, MSG_ID, st);
msg.sendToTarget();
To get the value in your handler,
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText((String) msg.obj);
break;
I would suggest you use a Bundle object instead of the raw object though. http://developer.android.com/reference/android/os/Message.html#setData(android.os.Bundle)
The reason you ends up with an empty string is because your handler and CommsThread run in different threads and thus not using the same instance of mClientMsg.
i.e. changes in CommsThread to mClientMsg is not visible in your handler.
Related
I have an app which has to poll a TCP server (on LAN) to fetch some data, I'm doing this using sockets in an AsyncTask class.
It works well for the first few requests. But at a certain point, the app must poll the server every 2s (using a timer). This is when the AsyncTask stops executing and the TCP messages do not get sent to the server. I can't figure out why.
Code is below. Any help will be appreciated!
Thank you!
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class TcpTask extends AsyncTask<String, Void, String> {
Context context;
TcpResultListener tcpResultListener;
int actionCode;
String TAG = "TcpTask";
String SERVER_IP = "192.168.1.12", SERVER_PORT = "1234";
Socket socket = null;
PrintWriter out;
int readTimeout;
// Creating listener
public void setOnTcpResultsListener(TcpResultListener tcpResultListener, int actionCode) {
this.tcpResultListener = tcpResultListener;
this.actionCode = actionCode;
}
// Constructor with context as parameter
public TcpTask(Context context, int timeout) {
this.context = context;
this.readTimeout = timeout;
}
#Override
protected String doInBackground(String... params) {
String result = null;
try {
//Create a client socket and define internet address and the port of the server
socket = new Socket(params[0], Integer.parseInt(params[1]));
Log.d(Constants.TAG, "Socket created");
//Setting timeout for readLine
socket.setSoTimeout(readTimeout);
Log.d(Constants.TAG, "Timeout set");
//Get the output stream of the client socket
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(Constants.TAG, "PrinterWriter created");
//Write data to the output stream of the client socket
out.println(params[2]);
Log.d(Constants.TAG, "Sending TCP data: " + params[2]);
//Get the input stream of the client socket
InputStream is = socket.getInputStream();
//Buffer the data coming from the input stream
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//Read data in the input buffer
result = br.readLine();
} catch (NumberFormatException e) {
Log.d("TcpException", e.toString());
} catch (UnknownHostException e) {
Log.d("TcpException", e.toString());
} catch (IOException e) {
Log.d("TcpException", e.toString());
}
try {
Log.d(Constants.TAG, "Socket:: " + socket);
if(socket != null){
socket.close();
}
} catch (IOException e) {
Log.d(Constants.TAG, e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
Log.d(Constants.TAG, "String:: " + result);
tcpResultListener.onResultsReceived(result, actionCode);
}
}
The method I use to call the AsyncTask:
void sendTCP(String msg) {
TcpTask tcpTask = new TcpTask(this, 8000);
// Setting listener for tcpTask to send back result
tcpTask.setOnTcpResultsListener(AddSpaceActivity.this, 1);
// TODO: Change the data being passed below
//Pass the server ip, port and client message to the AsyncTask
tcpTask.execute(gwIP, gwPort, msg);
}
EDIT: Timer code:
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d(Constants.TAG, "Timer fired:: " + firstReceived);
if(firstReceived){
sendTCP(Constants.NETWORK_STATUS_REQUEST);
}
}
}, 3000, 2000);
I have an android application which sends and receives UDP packets over WIFI.
the application send data to WIFI modem and then modem response to application by sending UDPpacket.
my app send data perfectly ,but unfortunately I cannot receive data from modem and show it on my screen.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class UdpConnectionWIFImodemActivity extends Activity {
final String strNetworkIP = "192.168.0.0";
final int intUDP_Port=8080;
private int sourceport=0;
class SocketListener implements Runnable
{
String str;
public void run()
{
DatagramSocket socket;
DatagramPacket packet;
byte[] buf = new byte[256];
System.out.println("Thread running");
if (sourceport!=0) {
try
{
socket = new DatagramSocket(sourceport);
while (true)
{
final TextView t = (TextView) findViewById(R.id.textView1);
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("Received packet");
String s = new String(packet.getData());
CharSequence cs = t.getText();
str = cs + "\r\n" + s;
t.post(new Runnable()
{
public void run()
{
t.setText(str);
}
}
);
}
}
catch (IOException e)
{
Log.e(getClass().getName(), e.getMessage());
}
}
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
Button send1 = (Button) findViewById(R.id.button1);
send1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String s = "1RPMONgetinfo";
try
{
final DatagramSocket socket = new DatagramSocket();
byte[] buf = new byte[256];
buf = s.getBytes();
InetAddress address = InetAddress.getByName(strNetworkIP);
final DatagramPacket packet = new DatagramPacket(buf, buf.length, address, intUDP_Port);
new Thread()
{
public void run()
{
try
{
System.out.println("About to send message");
socket.send(packet);
sourceport = socket.getLocalPort();
System.out.println("Sent message");
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
socket.close();
}
}.start();
}
catch (SocketException e1) {
}
catch (UnknownHostException e2) {
}
}
});
Thread t = new Thread(new SocketListener());
t.start();
}
}
I guess you have already solved your problem long time ago. But your problem seems to be the same as I had. The problem was that I bound the Socket false.
This is how it works for me:
InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getByName(*own IP address as String*), *own portnumber you want to listen to*);
Datagramsocket socket = new DatagramSocket(null);
socket.setReuseAddress(true);
socket.bind(inetSocketAddress);
byte[] message = new byte[4096];
DatagramPacket packet = new DatagramPacket(message, message.length);
socket.receive(packet);
btw: To test if I receive the answer packet on my tablet correctly I used the app: "UDP Sender /Receiver"
I am debugging my app on my Galaxy S3 and whenever I monitor the processing .. I notice very high load the app processing . Application processing goes to 80 % sometimes which is incredibly hight
Here is the 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.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
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 {
private boolean connected = false;
//private Handler handler = new Handler();
public TextView txt;
int doit=0;
protected SocketCore Conn;
public Button b;
public EditText TextToSend;
#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);
TextToSend = (EditText)findViewById(R.id.editText1);
//Conn = new SocketCore(this,txt);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("ErrorButton","Button Pressed Before Toggle"+doit);
doit=1;
Log.e("ErrorButton","Button Pressed "+doit);
}
});
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
public class ClientThread implements Runnable {
Socket socket ;
String finall="",text;
PrintWriter out = null;
BufferedReader in = null;
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.0.150");
Log.d("ClientActivity", "C: Connecting...");
socket= new Socket(serverAddr,4444);
connected = true;
while (connected) {
try {
if(doit==1)
{
Log.e("ErrorButton","If");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(TextToSend.getText().toString());
finall="";
while ((text = in.readLine()) != null) {
finall += text;
Log.e("Test","Final: "+finall);
if(text=="quit")
{
socket.close();
}
Log.e("ClientActivity", "After Read "+doit+" "+finall);
break;
}
doit=0;
Log.e("ClientActivity", "Out Of IF "+doit);
runOnUiThread(new Runnable() {
public void run() {
txt.setText(finall);
}
});
}
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
txt.setText("Closed Socket");
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
public void ClientHandler(String Send)
{
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
out.println(Send);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
finall = in.readLine();
txt.setText(finall);
}
catch(IOException e)
{txt.setText("Exception");}
}
}
}
The CPU is doing that because you're running a non-stop loop that keeps feeding runnables into the UI thread, so the CPU keeps under very high load. Instead, I'd recommend that you consider using a push strategy instead of a polling strategy with something like GCM (Google Cloud Messaging), where your app wakes up when your server pushes new data onto the device. If that's not a possible solution, I'd throttle the polling rate to a lower rate and limit it to a few times per minute (or less), using Thread.sleep() periodically in run() to avoid flooding the UI thread with runnables.
Fixed
With using Thread.Sleep(200);
while (connected) {
try {
Thread.sleep(200);
Log.e("ErrorButton","If");
if(doit==1)
{
I want to connect to my server building in Android, but I can't, I don't know how to connect it. I think my code is fine. I changed Manifest with Permission INTERNET.
package com.android.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private static String TAG = "ServerSocketTest";
EditText edittext1;
private ServerSocket server;
Runnable conn = new Runnable() {
public void run() {
try {
edittext1.setText("Esperando0");
server = new ServerSocket(9999);
edittext1.setText("Esperando1");
while (true) {
edittext1.setText("Esperando2");
Socket socket = server.accept();
if(socket.isConnected() == true){
edittext1.setText("socket is connected: " + socket.getRemoteSocketAddress().toString());
}
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Toast.makeText(getApplicationContext(), "BufferedReader ready", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
Log.i("received response from server", str);
edittext1.setText("Conectado");
PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
salida.println("Conexion establecida");
in.close();
socket.close();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
};
#SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
edittext1 = (EditText)findViewById(R.id.editText1);
Button boton1 = (Button)findViewById(R.id.button1);
boton1.setOnClickListener(this);
new Thread(conn).start();
}
#Override
protected void onPause() {
super.onPause();
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void onClick(View v) {
}
}
My client, it work very well.:
package com.clientesocketandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ClienteSocketAndroid extends Activity implements OnClickListener{
String IP,mensaje, MensajeEntrada;
int Port;
Socket socket;
ServerSocket SSocket;
PrintWriter out;
Button boton1, boton2,boton3;
EditText edittext1,edittext2,edittext3,edittext4;
TextView textview5;
String mClientMsg = "";
Thread myCommsThread = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente_socket_android);
boton1 = (Button)findViewById(R.id.button1);
boton1.setOnClickListener(this);
boton2 = (Button)findViewById(R.id.button2);
boton2.setOnClickListener(this);
boton3 = (Button)findViewById(R.id.button3);
boton3.setOnClickListener(this);
edittext1 = (EditText)findViewById(R.id.editText1);
edittext2 = (EditText)findViewById(R.id.editText2);
edittext3 = (EditText)findViewById(R.id.editText3);
edittext4 = (EditText)findViewById(R.id.editText4);
Port = Integer.parseInt(edittext3.getText().toString());
try {
SSocket = new ServerSocket(Port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket = SSocket.accept();
Toast.makeText(getApplicationContext(), "Listo", Toast.LENGTH_SHORT).show();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
MensajeEntrada = in.readLine();
edittext4.setText(MensajeEntrada);
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
public void onClick(View arg0) {
if(arg0.getId() == R.id.button1){
try {
IP = edittext2.getText().toString();
Port = Integer.parseInt(edittext3.getText().toString());
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
socket = new Socket(IP, Port); //Abre un socket con el número de IP y de puerto.
if(socket.isConnected() == true){
Toast.makeText(getApplicationContext(), "Conectado", Toast.LENGTH_SHORT).show();
}
} catch (UnknownHostException e) {
e.printStackTrace();
edittext1.setText(e.getMessage() + ": " + e.getCause());
} catch (IOException e) {
e.printStackTrace();
edittext1.setText(e.getMessage() + ": " + e.getCause());
}
}
if(arg0.getId() == R.id.button3){
try {
mensaje = edittext1.getText().toString();
PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
salida.println(mensaje);
edittext1.setText("");
//hace falta concatenacion
edittext4.setText("" + "\n" + mensaje + "");
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Mensaje NO enviado", Toast.LENGTH_SHORT).show();
}
}
if(arg0.getId() == R.id.button2){
try {
PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
salida.println("bye");
Toast.makeText(getApplicationContext(), "Conexión cerrada", Toast.LENGTH_SHORT).show();
socket.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error al cerrar sesion", Toast.LENGTH_SHORT).show();
}
}
}
}
I thank your Help!!
The algorithm shows that whenever your socket is connected or not, you always create a buffered i/O stream and sending the data
The following is my suggested pseudo code for server
try(socket successfully connected) {
try( server is synchronized with the client) socket.accept();
// create the Object I/O stream
} show error
for Client
//Create a new socket with IP address and port number
try
client connect to server with aforementioned parameters with timeout
create a Object I/O stream
catch (IOException)
One problem that I see with your code is, you cannot update Ui elements from Non Ui thread, that is why it is raising exception, but you have caught all the exceptions.
So remove all setText calls from the runnable.
edittext1.setText("Conectado");
Use runonUithread or any other methods to update UI elements, and do not catch all exceptions like you have done. It is quite difficult to debug.
I have problem with android sockets , I have two android applications Server and ServerClient , in ServerClient It gives nullPointerException on second row written below
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
I checked serverAddr is 10.0.2.2 , but then I saw that socket is null. Can anybody helps with it?
EDIT: with this serverAddress I saw that it is unreachable, maybe I must make it reachable manual ?
here is sources
*ServerClient*
package com.example.serverclient;
import android.os.Bundle;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
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.util.Log;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import android.view.Menu;
public class MainActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "10.0.2.2";
private static final int REDIRECTED_SERVERPORT = 5000;
// AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
// PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
// PORT 6000
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
OutputStream sk = socket.getOutputStream();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
}
**Server**
package com.example.myserver;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText("Nothing from client yet");
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText(mClientMsg);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Have you made sure that you aren't getting an UnknownHostException or a IOException? One of those has to be getting called otherwise socket would not be null.
Change (Exception e) of the error 3 para to NullPointerException and then run the client side and send a message. Error 3 will no longer be displayed on the screen and you will receive the message on Myserver.
Exception e --> NullPointerException
This class returns your response, but also needs permission of internet in manifest file.
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}