my android application needs to communicate with a server python but at the time to receive a response, the answer does not come. These are my codes:
This is my Client:
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 5589;
private static final String SERVER_IP = "192.168.1.131";
TextView risp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
risp = (TextView) findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
out.flush();
// Read from sock
BufferedReader input = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = input.readLine()) != null) {
response.append(line);
}
risp.setText(risp.getText().toString() + " " + response.toString());
out.close();
input.close();
socket.close();
} 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();
}
}
}
And this is the Server:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('192.168.1.131', 5589)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data
while True:
data = connection.recv(1024)
if data.lower() != 'q':
print "<-- client: ", data
else:
print "Quit from Client"
connection.close()
break
data = raw_input("--> server: ")
if data.lower() != 'q':
connection.sendall(data)
else:
print "Quit from Server"
connection.close()
break
finally:
# Clean up the connection
print "Connection close"
connection.close()
The server receive the client message, but the client doesn't receive the server message. Why?
Thanks all in advance
EDIT: I SOLVED it this way:
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 5589;
private static final String SERVER_IP = "192.168.1.131";
TextView risp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
risp = (TextView) findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
new ConnectionTask().execute();
}
class ConnectionTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
String responce = null;
try {
EditText et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
out.flush();
InputStream input = socket.getInputStream();
int lockSeconds = 10*1000;
long lockThreadCheckpoint = System.currentTimeMillis();
int availableBytes = input.available();
while(availableBytes <=0 && (System.currentTimeMillis() < lockThreadCheckpoint + lockSeconds)){
try{Thread.sleep(10);}catch(InterruptedException ie){ie.printStackTrace();}
availableBytes = input.available();
}
byte[] buffer = new byte[availableBytes];
input.read(buffer, 0, availableBytes);
responce = new String(buffer);
out.close();
input.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return responce;
}
protected void onPostExecute(String responce) {
risp.setText(responce);
}
}
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();
}
}
}
}
Related
I am implementing a socket application where one phone will be a client and the other will be a server. The program is able to send strings using print writer just fine from the client to the sever but when i try to send an image file, it throws an exception. I'd really appreciate if someone could help me out.
Here is the code for the server
public class ServerActivity extends Activity {
private TextView serverStatus;
private ImageView profile;
// DEFAULT IP
public static String SERVERIP = "10.0.2.15";
// DESIGNATE A PORT
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
profile = (ImageView) findViewById(R.id.image);
String filepath = "/sdcard/DCIM/time table.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
profile.setImageBitmap(bm);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
//String line;
byte [] line;
Bitmap bitmap;
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
/*InputStream in = client.getInputStream();
line = null;
in.read(line);
Log.d("ServerActivity", line.toString());
bitmap = BitmapFactory.decodeByteArray(line , 0, line.length);*/
int bytesRead;
int current = 0;
int filesize=65383;
byte [] mybytearray2 = new byte [filesize];
InputStream is = client.getInputStream();
FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/IMG-20130112-WA0011.jpeg"); // destination path and name of file
//FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray2, current, (mybytearray2.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray2, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
//System.out.println(end-start);
bos.close();
handler.post(new Runnable() {
#Override
public void run() {
profile.setImageBitmap(bitmap);
//serverStatus.setText(line);
}
});
/*BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText(line);
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
}
});
}*/
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
#Override
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the client side code
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
private Socket socket;
private ImageView profile;
private byte [] imgbyte;
String filepath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
profile = (ImageView) findViewById(R.id.imageView1);
filepath = "/sdcard/small.jpg";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
imgbyte = getBytesFromBitmap(bm);
profile.setImageBitmap(bm);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected) {
try {
/*File myFile = new File (filepath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = socket.getOutputStream();
Log.d("ClientActivity", "C: Sending command.");
//System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();*/
Log.d("ClientActivity", "C: Sending command.");
/*PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);*/
// WHERE YOU ISSUE THE COMMANDS
OutputStream output = socket.getOutputStream();
Log.d("ClientActivity", "C: image writing.");
output.write(imgbyte);
output.flush();
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
socket.close();
connected = false;
} catch (IOException e) {
e.printStackTrace();
}
}
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
}
update:
The exception is thrown at the server side code. Its the exception which reads :"Oops. Connection interrupted. Please reconnect your phones."
This is the exception that is thrown:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Thanks everyone , I found the error.
The toast messages have to be inside the UI thread or the handler . As I had a few of them in a non UI thread, it began to throw the exception.
I cant create a simple TCP connection to my server.
I created a AsyncTask to send messages, but it didn't work.
I added INTERNET and ACCESS_NETWORK_STATE to the permissions.
I don't know what else to try.
public class ServerCommunicator extends AsyncTask<String,Void,Void>{
public static String SERVER_IP = "192.168.2.148";
public static int SERVER_PORT = 1337;
public static String SERVER_PW = "adsfadsf";
public Context context;
#Override
protected Void doInBackground(String... params) {
//Create Command
CommandFactory cmdFactory = new CommandFactory();
Command cmd = cmdFactory.createCommand();
System.out.println("Cmd created..");
//-----
try {
System.out.println(SERVER_IP);
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
System.out.println("Created serverAddr "+ SERVER_IP);
Socket socket = new Socket(serverAddr,SERVER_PORT);
System.out.println("Socket created..");
//sends the message to the server
PrintWriter mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String msg2Send = Crypter.Encrypt(cmd.toString(), SERVER_PW);
sendMsgAsByteArr(socket, msg2Send);
Command recCmd = cmdFactory.extractCommandFromStr(receiveMsg(socket));
socket.close();
Toast.makeText(context, recCmd.id, Toast.LENGTH_LONG).show();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static void sendMsgAsByteArr(Socket socket, String msg) {
try {
socket.getOutputStream().write(msg.getBytes());
System.out.println("sent cmd..");
} catch (IOException e) {
e.printStackTrace();
}
}
private static String receiveMsg(Socket socket) {
String msg = "";
int c;
ArrayList<Byte> incoming = new ArrayList<Byte>();
try {
while((c = socket.getInputStream().read())!=-1) {
incoming.add((byte)c);
}
byte[] allBytes = new byte[incoming.size()];
for(int i = 0; i < incoming.size(); i++) {
allBytes[i] = incoming.get(i);
}
msg = new String(allBytes);
} catch (IOException e) {
e.printStackTrace();
}
return msg;
}
}
My program runs till Socket socket = new Socket(serverAddr, SERVER_PORT); then it stops. It doesn't show any stack trace or errors.
Any ideas?
I debugged your code, and while there were multiple issues, none were related to Android 6.
I created a simplified version of your code and got it working.
One issue is that your context reference was null, so I set it in the constructor.
Another issue is that you were trying to show a Toast on a background thread, which won't work.
Another issue was your send and receive methods, they didn't work for me.
Here's the simplified code that I got working with a TCP/IP server, tested on both Android 4.4.4 and Android 6.
You can take this and expand on it as needed:
public class ServerCommunicator extends AsyncTask<String,Void,String> {
public static String SERVER_IP = "11.222.33.444";
public static int SERVER_PORT = 1234;
public Context context;
public ServerCommunicator(Context c) {
this.context = c;
}
#Override
protected String doInBackground(String... params) {
try {
System.out.println(SERVER_IP);
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
System.out.println("Created serverAddr "+ SERVER_IP);
Socket socket = new Socket(serverAddr,SERVER_PORT);
System.out.println("Socket created..");
//sends the message to the server
PrintWriter mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String msg2Send = "{\"HelloWorld\", \"1234\"}";
mBufferOut.println(msg2Send);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String result = in.readLine();
System.out.println("result: " + result);
socket.close();
return result;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}
This question already has answers here:
Android: Image received over socket is corrupted
(2 answers)
Closed 8 years ago.
Hi I'm having problem receiving an image
In the last while it simply doesn't receive all the bytes and the program does not exit the while condition. With a 77970 bytes image, this receives 61592 bytes then just does nothing. It keeps stuck in the while. I dunno what to do, thanks for any help.
public class FileActivity extends Activity {
private EditText serverIp, getPort, exT;
private Button connectPhones;
private TextView tv, tvIP;
private Boolean connected = false;
private String serverIpAddress, portStr,ex;
private Socket socket;
private int port, len;
private String filepath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
exT = (EditText) findViewById(R.id.editText1);
tvIP = (TextView) findViewById(R.id.IPtv);
tv = (TextView) findViewById(R.id.Portatv);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
getPort = (EditText) findViewById(R.id.server_port);
}
public void connectListener(View v)
{
tv.setVisibility(View.GONE);
connectPhones.setVisibility(View.GONE);
getPort.setVisibility(View.GONE);
serverIp.setVisibility(View.GONE);
tvIP.setTextSize(16f);
tvIP.setText("Connesso");
exT.setVisibility(View.GONE);
ex = exT.getText().toString();
if (!connected) {
serverIpAddress = serverIp.getText().toString();
portStr = getPort.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
public class ClientThread implements Runnable
{
#Override
public void run() {
// TODO Auto-generated method stub
port = Integer.parseInt(portStr);
socket = new Socket();
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connessione in corso...");
socket = new Socket(serverAddr, port);
Log.d("ClientActivity", "C: Connesso!");
connected = true;
DataInputStream dis;
try {
dis = new DataInputStream(socket.getInputStream());
int bytes;
byte[] b = new byte[32];
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String l = in.readLine();
//String line = Integer.toString(l);
Log.d("PROVA", l);
try
{
len = Integer.parseInt(l); Log.d("CLIENT", Integer.toString(len));
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
byte[] img = new byte[1024]; //1082922
FileOutputStream fos = new FileOutputStream("/sdcard/" + ex);
BufferedOutputStream bos = new BufferedOutputStream(fos);
/*bytes = dis.read(img, 0, img.length);
bos.write(img, 0, img.length);*/
int count = 0;
while ((bytes = dis.read(img)) != -1) {
count += bytes;
Log.d("CLIENT", Integer.toString(count));
Log.d("TEST", Integer.toString(bytes));
//Write to file
bos.write(img, 0, bytes);
}
//bos.flush();
//bos.close();
Log.d("TCP", "Save to file");
} catch(IOException e){
e.printStackTrace();
}
} catch (Exception e) {
Log.e("ClientActivity", "C: Errore", e);
connected = false;
}
}
}
#Override
protected void onStop() {
super.onStop();
if(connected == true)
{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Server:
public class FileActivity extends Activity {
private String test;
private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private byte [] mybytearray;
private String tmp = null;
private TextView tv;
private File myFile;
private int l;
private String path;
private EditText editText;
private ServerSocket serverSocket;
private Socket client;
public static String SERVERIP = "10.0.2.15";
private final int SERVERPORT = 8080;
private byte [] imgbyte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
tv = (TextView) findViewById(R.id.textView1);
editText = (EditText) findViewById(R.id.editText1);
SERVERIP = getLocalIpAddress();
Thread sThread = new Thread(new ServerThread());
sThread.start();
}
public void sendListener(View v) {
tmp = editText.getText().toString();
path = "/sdcard/" + tmp;
myFile = new File(path);Log.d("SERVER", "WORKS");
if(myFile.exists())
{
l = (int) myFile.length();Log.d("SERVER", "WORKS");
tv.setText(path + " Size:" + Integer.toString(l));
tmp = Integer.toString(l); Log.d("SERVER", "WORKS");
test = tmp;
Thread t = new Thread(new sSend());
t.start();
}
else
{
tv.setText("Il file non esiste");
}
}
public class sSend implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
out.println(test);
//out.close();
Log.d("SERVER", "WORKS");
byte[] mybytearray = new byte[1024]; //create a byte array to file
Log.d("SERVER", "WORKS");
fileInputStream = new FileInputStream(myFile);
bufferedInputStream = new BufferedInputStream(fileInputStream);
Log.d("SERVER", "WORKS");
//bufferedInputStream.read(mybytearray, 0, mybytearray.length); //read the file
Log.d("SERVER", "WORKS");
try{
outputStream = client.getOutputStream();
} catch(Exception e)
{
Log.d("OUTPUT", "UFFFF");
e.printStackTrace();
}
Log.d("SERVER", "WORKS");
int count = 0;
int size = 0;
while((count = bufferedInputStream.read(mybytearray, 0 , mybytearray.length)) != -1)
{
// count = bufferedInputStream.read(mybytearray, 0 , mybytearray.length);
size += count;
Log.d("SERVER", "SEND");
try{
outputStream.write(mybytearray, 0, count);
} catch(Exception e) {
e.printStackTrace();
}
Log.d("TEST", Integer.toString(count));
}
Log.d("SERVER", "DONE");
Log.d("SERVER", Integer.toString(size));
}catch(Exception e){
e.printStackTrace();
}
}
}
public class ServerThread implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(SERVERPORT);
client = serverSocket.accept();
//outputStream = client.getOutputStream();
Log.d("SERVER", "Connesso");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("TEST", "UFFFAAA");
}
}
}
private String getLocalIpAddress() {
String tmp = "";
int i = 0;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress())
{
tmp += "IP: " + inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return tmp;
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This looks like a repost. Why did you start a new thread? The other one was not ready yet. We had discovered some problems and you do not even mention them here. OP tries to send file size first and then the content. Also the client should read the file size first but it is a complete mess.
I read a thread on the same topic : connecting 2 Emulator Instances
Server Side Code listening on port 6000:
public class NewServerActivity 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.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();
}
}
}
}
}
Client side code :
public class NewClientActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "10.0.2.2";
// AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
// PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
// PORT 6000
private static final int REDIRECTED_SERVERPORT = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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();
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();
}
}
});
}
}
I applied server code on one emulator and client code on another emulator.
Redirected the ports :
telnet localhost 5554
redir add tcp:5000:6000
I ran the server on emulator 5554 and the client on 5556.
My client side is working fine but unfortunately, on starting the server app the emulator shows a message Unfortunately APPLICATION was stopped. And eclipse shows a java.lang.NullPointerException at "s = ss.accept();" line.
Is it somehow related to the configuration of my AVD.
Post your code and the stack trace.
From the one line you posted it sounds like 'ss' is null and you're trying to call accept() on a null.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void mOnClick(View v) {
switch (v.getId()) {
case R.id.myButton:
new Thread(new Runnable() {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
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);
Log.d("Client", "Client sent message");
out.close();
socket.close();
} catch (UnknownHostException e) {
//tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
//tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
//tv.setText("Error3");
e.printStackTrace();
}
}
}).start();
break;
}
}
need xml change
android:onClick="mOnClick"
<Button
android:id="#+id/myButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="mOnClick"
android:text="start" />
it's because try to run connect() method in main Thread
I have an android client and a java server that use the same socket to send each other a string, but actually doesn't work and I don't know why.
Anyway, I need to use just one socket.
Here's the code for client and server:
public class CliActivity extends Activity implements OnClickListener {
Button b;
TextView tv;
BufferedReader in = null;
PrintStream out = null;
Socket client = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b =(Button)findViewById(R.id.button1);
tv =(TextView)findViewById(R.id.textView1);
b.setOnClickListener(this);
}
public void onClick(View v) {
try {
client = new Socket("192.168.0.3",9000);
out = new PrintStream(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out.write(("How are you?").getBytes());
out.close();
String message = in.readLine();
tv.setText(message);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server:
public class server {
public static void main(String[] args) {
BufferedReader in = null;
PrintStream out = null;
Socket client = null;
try {
ServerSocket server = new ServerSocket(9000);
client = server.accept();
out = new PrintStream(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String message = in.readLine();
System.out.println(message);
out.write(("fine thanx").getBytes());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Any suggestion?