Good day I tried to connect two android phones by Socket. I have two different applications (the server and client). Server consist of one Activity
public class ShareCameraActivity extends Activity {
/** Called when the activity is first created. */
private TextView serverStatus;
// default ip
public static String SERVERIP = "10.0.2.15";
// designate a port
public static final int SERVERPORT = 12345;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
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 {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
#Override
public void run() {
// 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 client is
public class ShareCameraClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "10.48.97.53";
private boolean connected = false;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
}
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 {
serverIpAddress = "10.48.97.53";
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
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;
}
}
}
}
Server works fine and take my his IP adress, but, client don't whant to connect him, and alweys go to exeption that connection is timeout.
Related
I am creating an app the will require people to connect to each other over WiFi to enable them to play together.
However i don't want to search for a person by IP address i want to search for all the people hosting a game currently and update a list of those people from which i can click on to connect.
Server
public class server extends AppCompatActivity {
int numPlayers=0;
int count = 0;
TextView infoip, msg;
String message = "";
ServerSocket serverSocket;
private String name="server";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
Bundle b = this.getIntent().getExtras();
numPlayers = b.getInt("numPlayers");
//name = b.getString("name");
infoip = (TextView) findViewById(R.id.serverText);
msg = (TextView) findViewById(R.id.serverPlayerCount);
infoip.setText("Hosting...");
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
ButtClickListener();
}
#Override
protected void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
super.onDestroy();
}
}
private void ButtClickListener() {
Button cancel = (Button) findViewById(R.id.severQuit);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private class SocketServerThread extends Thread
{
static final int SocketServerPORT = 8080;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
server.this.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
server.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;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
count = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "You are the #" + count+" person out of "+count+"/"+numPlayers;
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += msgReply + "\n";
server.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
} catch (IOException e) {
e.printStackTrace();
message += "Error " + e.toString() + "\n";
}
server.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
}
}
private String getIpAddress() {
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;
}
}
Client
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Socket socket = new Socket(serverAddr,
8080);
connected = true;
while (connected) {
try {
} catch (Exception e) {
}
}
socket.close();
} catch (Exception e) {
connected = false;
}
}
}
The above code is to be implemented when i find a server by clicking on it i will be able to connect to the server by the name, but i don't know how to search for the servers.
How would i go about modifying the client side so when it runs it will search for all potential servers and return a list of server names?.
Thanks.
I think this is an excellent usecase for Network Service Discovery http://developer.android.com/training/connect-devices-wirelessly/nsd.html
This question has been asked quite a few times here , but there is no good answer yet.So I am just posting this question along with my progress. I would like to know if there is a way to perform socket programming between a real device and emulator.
I referred to android developer page : http://developer.android.com/tools/devices/emulator.html
to establish communication between two android devices / and also between two emulators. But there is no way I am able to send data from android device(client) to emulator(as the server). Both of them are connected to the same network and are able to ping each other.
public class ServerActivity extends Activity {
private TextView serverStatus;
private Button Start;
private Button Mark;
private Button Stop;
// DEFAULT IP
public static String SERVERIP = "10.0.2.15";
// DESIGNATE A PORT
public static final int SERVERPORT = 6000;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverStatus = (TextView) findViewById(R.id.server_status);
Start = (Button)findViewById(R.id.start);
Mark = (Button)findViewById(R.id.mark);
Stop = (Button)findViewById(R.id.stop);
//SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP +" "+ SERVERPORT);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// LISTEN FOR INCOMING CLIENTS
final Socket client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
handler.post(new Runnable() {
#Override
public void run() {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
Log.d("ServerActivity", "S: Sending command.");
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
out.println("HeyClient!");
Log.d("ServerActivity", "S: Sent.");
Start.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
//send click command to start recording to client
}
});
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
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 the client code :
public class ClientActivity extends Activity {
private EditText serverIp;
private TextView serverCommand;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
serverCommand = (TextView)findViewById(R.id.server_commands);
}
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 socket = new Socket(serverAddr, 80);
connected = true;
while (connected)
{
try {
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((line = in.readLine()) != null) {
Log.d("ClientActivity", line);
serverCommand.setText(line);
if (line == "start")
{
}
}
} 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;
}
}
}
}
I also set up port forwarding to direct incoming connections from android at port 80 to emulator at port 6000. This is was done using telnet.
For some reason, all this doesn't seem to make emulator connect to the incoming connections.
I would be really grateful if someone could help me out.
Credits : Code from http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/
I am developing a TCPclient for Android device.
I can connect to a server and I can track that I receive message from the server.
I would like to display the result sent by the server on the client GUI with the TextView textview_textin
Could you help me to do that
Thanks a lot
public class JssclientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "192.168.0.2";
private boolean connected = false;
private TextView textview_textin;
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 2600);
connected = true;
while (connected) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inMsg = "";
char buf[] = null;
int val = in.read();
while (-1 != val) {
inMsg = in.readLine();
}
} 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;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview_textin = (TextView) findViewById(R.id.textin);
connectPhones = (Button) findViewById(R.id.connect);
connectPhones.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
//serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
});
}
}
Thanks a lot for your replies
I can connect to the device but I receive nothing. I don't know why?
Here what I tried,
public class JssclientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "192.168.20.21";
private boolean connected = false;
private TextView textview_textin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview_textin = (TextView) findViewById(R.id.textin);
connectPhones = (Button) findViewById(R.id.connect);
ClientThread ct = new ClientThread(new ClientThread.SocketCallback() {
public void onReceived(final String msg) {
JssclientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
textview_textin.setText(msg);
}
});
}
});
}
}
class ClientThread implements Runnable {
interface SocketCallback {
void onReceived(String msg);
}
private SocketCallback callback;
private boolean connected;
private Socket socket;
public ClientThread(ClientThread.SocketCallback cb) {
this.callback = cb;
try {InetAddress serverAddr = InetAddress.getByName("192.168.20.21");
Log.d("ClientActivity", "C: Connecting...");
//Socket
socket = new Socket(serverAddr, 2600);
connected = true;
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
public void run() {
while (connected) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inMsg = "";
char buf[] = null;
int val = in.read();
// while (-1 != val) {
// inMsg = in.readLine();
// }
while (-1 != val) {
inMsg = in.readLine();
this.callback.onReceived(inMsg);
}
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
// socket.close();
Log.d("ClientActivity", "C: Closed.");
}
}
Please could you help me?
Thanks
create a callback class,
interface SocketCallback {
void onReceived(String msg);
}
this can be an inner of ClientThread, as they are logically related. that's not required but it's good design.
have your Runnable class accept an instance of this callback in it's constructor.
public ClientThread(ClientThread.SocketCallback cb) {
this.callback = cb;
}
when you construct your Runnable (ClientThread), do so from your UI class (JssClientActivity), like this,
ClientThread ct = new ClientThread(new ClientThread.SocketCallback() {
public void onReceived(String msg) {
JssClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myTextView.setText(msg);
}
});
}
}};
finally, in ClientThread, when you receive a message, call the callback,
while (-1 != val) {
inMsg = in.readLine();
this.callback.onReceived(inMsg);
}
note that you cannot update the UI from the thread where ClientThread is running. it must be updated from the UI thread, hence the call to runOnUiThread().
You can set the text of a TextView by using the setText() method of it.
Example:
textview_textin.setText(yourText)
By using runOnUiThread() you will be able to access your TextView. See this answer.
I have the a Server/Client application in which i want to send and display screenshot of server on client. Can any body help me in that. thanks
The code is the following
Server side
public class ServerActivity extends Activity {
private TextView serverStatus;
RelativeLayout mainLayout;
// 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);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
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");
mainLayout = (RelativeLayout)findViewById(R.id.screen);
ImageView iv =(ImageView)findViewById(R.id.iv);
File root = Environment.getExternalStorageDirectory();
File file = new File(root,"androidlife.jpg");
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(), mainLayout
.getHeight(), Bitmap.Config.ARGB_8888);
iv.setImageBitmap(b);
Canvas c = new Canvas(b);
mainLayout.draw(c);
//serverStatus.setText("Screenshot is displaying");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
//receive a message
String incomingMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpServer", "received: " + incomingMsg);
serverStatus.setText("received: " + incomingMsg);
//send a message
String outgoingMsg = "goodbye from port " + SERVERPORT + System.getProperty("line.separator");
out.write(outgoingMsg);
//out.flush();
Log.i("TcpServer", "sent: " + outgoingMsg);
serverStatus.setText("sent: " + outgoingMsg);
//while ((line = in.readLine()) != null)
handler.post(new Runnable() {
#Override
public void run() {
}
});
// }
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();
}
}
}
Client side code is:
public class ClientActivity extends Activity {
public EditText serverIp;
public TextView tv;
private Button connectPhones;
private String serverIpAddress = "";
private static final int SERVERPORT = 8080;
private boolean connected = false;
//private Handler handler = new Handler();
#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);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
// if(true)
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 socket = new Socket(serverAddr, SERVERPORT);
connected = true;
while (connected) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//send output msg
String outMsg = "TCP connecting to " + SERVERPORT + System.getProperty("line.separator");
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
//accept server response
String inMsg = in.readLine() + System.getProperty("line.separator");
tv.setText("message from server"+ inMsg);
Log.i("TcpClient", "received: " + inMsg);
// ImageView iv = (ImageView)findViewById(R.id.iv);
// iv.setImageBitmap(bm);
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;
}
}
}
}
I don't see in your code where where you are trying to send the Bitmap of image or screen shot!! and you cannot send send a Bitmap over socket you should add this in the sender side after creating the bitmap b to create a byte array out of the bitmap:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
In the server side receiver the bytearray and then recreat the bitmap in this way:
Bitmap breceived = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
I want to send a file from client to Server by using Socket Programming.
I unable to transfer this file, client side is giving message OK, server get freeze at serverClient.accept,and only dispalys Listening on
Ip: 10.81.81.125, I am so confused, Kindly help.
Thanks in advance.
Client Code:
public class uploadData extends AsyncTask<String, String, String> {
#Override
public void onPreExecute() {
} catch (Exception e) {
}
}
#Override
protected String doInBackground(String... arg0) {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, Constants.SERVERPORT);
socket.setSoTimeout(90000);
connected = true;
if (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
try {
// where you issue the commands
File sFile = new File(filePath);
BufferedInputStream buffIn = null;
buffIn = new BufferedInputStream(
new FileInputStream(sFile));
out.print(buffIn);
} catch (Exception e) {
// TODO: handle exception
}
// setText();
// 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) {
e.printStackTrace();
Toast.makeText(SynServer.this,getString(R.string.noServer), Toast.LENGTH_SHORT).show();
connected = false;
}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
// TODO Auto-generated method stub
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
#Override
protected void onDestroy() {
Runtime.getRuntime().gc();
super.onDestroy();
}
}
Server Code:
public class Socket_File_ServerActivity extends Activity {
private TextView serverStatus;
// default ip
public static String SERVERIP = "10.0.2.15";
// designate a port
public static final int SERVERPORT =12345;
private Handler handler = new Handler();
private ServerSocket serverSocket;
Socket client=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
//
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
Looper.prepare();
if (SERVERIP != null) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString()
, Toast.LENGTH_LONG).show();
serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString());
}
});
Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString()
, Toast.LENGTH_LONG).show();
serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString());
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
final String myline=new String(line);
handler.post(new Runnable() {
public void run() {
// tv_chatbox.setText("Client said:="+myline);
// do whatever you want to the front end
// this is where you can be creative
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (final Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Error"+e.getMessage());
}
});
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();
}
}
}
Client
public class TCPServer {
//tcp port on local host port
public static final int PORT = 3100;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
//server socket, can also specify Host Address
serverSocket = new ServerSocket(PORT);
//start listening on port
System.out.println("Listening for clients on port: " + PORT);
} catch (IOException e) {
System.err.println("Could not listen on port: " + PORT);
System.err.println(e.getMessage());
System.exit(-1);
}
//create new thread pool
ThreadPool threadPool = new ThreadPool(2);
//call runnable method on thread pool
threadPool.runTask(startServer(serverSocket));
//join thread pool
threadPool.join();
//close server socket and destroy threadpool
serverSocket.close();
threadPool.destroy();
}
private static Runnable startServer(final ServerSocket socket) {
return new Runnable() {
#Override
public void run() {
//keep looping and looking for data
while (true)
try {
//create new thread
new TCPServerThread(socket.accept()).start();
} catch (IOException e) {
System.out.println("Client got disconnected!" + "\nListening for clients on port: " + PORT);
}
}
};
}
}
Server
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
public class TCPServerThread extends Thread {
private Socket socket = null;
//constructor
public TCPServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
//read data into buffered stream
BufferedInputStream stream = new BufferedInputStream(
socket.getInputStream());
//create music player object with buffered stream
Player p = new Player(stream);
//start playing
p.play();
//close socket after done playing
socket.close();
} catch (IOException e) {
System.out.println("Client got disconnected!" + "\nListening for clients on port: " + TCPServer.PORT);
} catch (JavaLayerException e) {
System.out.println("Client got disconnected!" + "\nListening for clients on port: " + TCPServer.PORT);
}
}
}
Thread Pool
import java.util.LinkedList;
class ThreadPool extends ThreadGroup {
private boolean isAlive;
private LinkedList<Runnable> taskQueue;
private int threadID;
private static int threadPoolID;
//constructor
public ThreadPool(int numThreads) {
super("ThreadPool-" + (threadPoolID++));
// Changes the daemon status of this thread group.
setDaemon(true);
isAlive = true;
taskQueue = new LinkedList<Runnable>();
for (int i = 0; i < numThreads; i++) {
new PooledThread().start();
}
}
public synchronized void runTask(Runnable task) {
if (!isAlive) {
throw new IllegalStateException();
}
if (task != null) {
taskQueue.add(task);
notify();
}
}
protected synchronized Runnable getTask() throws InterruptedException {
while (taskQueue.size() == 0) {
if (!isAlive) {
return null;
}
wait();
}
return (Runnable) taskQueue.removeFirst();
}
public synchronized void close() {
if (isAlive) {
isAlive = false;
taskQueue.clear();
interrupt();
}
}
public void join() {
// notify all waiting threads that this ThreadPool is no
// longer alive
synchronized (this) {
isAlive = false;
notifyAll();
}
// wait for all threads to finish
Thread[] threads = new Thread[activeCount()];
int count = enumerate(threads);
for (int i = 0; i < count; i++) {
try {
threads[i].join();
} catch (InterruptedException ex) {
}
}
}
private class PooledThread extends Thread {
public PooledThread() {
super(ThreadPool.this, "PooledThread-" + (threadID++));
}
public void run() {
while (!isInterrupted()) {
// get a task to run
Runnable task = null;
try {
task = getTask();
} catch (InterruptedException ex) {
}
// if getTask() returned null or was interrupted,
// close this thread by returning.
if (task == null) {
return;
}
// run the task, and eat any exceptions it throws
try {
task.run();
} catch (Throwable t) {
uncaughtException(this, t);
}
}
}
}
}