how to send message to all connected client from server - android

i've created an android application in which, android application act as the client, and server resides in the desktop application.
suppose there are 10 android application runs the same at a time on 10 different android tablets, when one updation received from one tablet, the desktop application sends the updation to all other remaining tablets. how could the server knows how many clients are connected and how to send the message to all the clients
what i plan is to run a server in all android so that when one updation received from one tablet, the desktop application sends the updation to all other remaining tablets.
can anyone please tell me some suggestion regarding this.
Client side
private int SERVER_PORT = 9999;
class Client implements Runnable {
private Socket client;
private PrintWriter out;
private Scanner in;
#Override
public void run() {
try {
client = new Socket("localhost", SERVER_PORT);
Log.d("Client", "Connected to server at port " + SERVER_PORT);
out = new PrintWriter(client.getOutputStream());
in = new Scanner(client.getInputStream());
String line;
while ((line = in.nextLine()) != null) {
Log.d("Client", "Server says: " + line);
if (line.equals("Hello client")) {
out.println("Reply");
out.flush();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Server class
class ServerThread implements Runnable {
private ServerSocket server;
#Override
public void run() {
try {
server = new ServerSocket(SERVER_PORT);
Log.d("Server", "Start the server at port " + SERVER_PORT
+ " and waiting for clients...");
while (true) {
Socket socket = server.accept();
Log.d("Server",
"Accept socket connection: "
+ socket.getLocalAddress());
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
private Socket clientSocket;
private PrintWriter out;
private Scanner in;
public ClientHandler(Socket clietSocket) {
this.clientSocket = clietSocket;
}
#Override
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream());
in = new Scanner(clientSocket.getInputStream());
String line;
Log.d("ClientHandlerThread", "Start communication with : "
+ clientSocket.getLocalAddress());
out.println("Hello client");
out.flush();
while ((line = in.nextLine()) != null) {
Log.d("ClientHandlerThread", "Client says: " + line);
if (line.equals("Reply")){
out.print("Server replies");
out.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

You could save the Sockets in a List and send a message through all the OutputStreams in that List:
Socket socket = Server.accept();
sockets.add(socket); //sockets is an ArrayList<Socket>
public void sendMessageToEveryone(String msg) {
for(Socket s : sockets) {
s.getOutputStream().write(msg.getBytes());
s.getOutputStream().flush();
}

You could use the Google Cloud Messaging service.
Take a look at this page:
https://developer.android.com/google/gcm/index.html

Related

How to set a virtual scene image programmatically on android emulator

I have writing some driven tests to a flutter project and there are a barcode scanner functionality which I can test successfully using the virtual scene tool provided by android emulator.
However there are many cases to test regarding to different barcodes. I want to set a specific barcode image on virtual scene to each case. Is it possible?
I found that the value of this image is putted on ~/.android/avd/[emulatorName]/AVD.conf file at virtualscene\posters variable.
virtualscene\posters=#Variant(\0\0\0\b\0\0\0\x2\0\0\0\b\0w\0\x61\0l\0l\0\0\0\n\xff\xff\xff\xff\0\0\0\n\0t\0\x61\0\x62\0l\0\x65\0\0\0\n\xff\xff\xff\xff)
virtualscene\posters=#Variant(\0\0\0\b\0\0\0\x2\0\0\0\b\0w\0\x61\0l\0l\0\0\0\n\ 0\0\0\\\0/\0U\0s\0\x65\0r\0s\0/\0l\0\x65\0o\0n\0\x61\0r\0\x64\0o\0.\0\x61\0r\0m\0\x65\0r\0o\0/\0\x44\0\x65\0s\0k\0t\0o\0p\0/\0J\0\x61\0m\0\x65\0s\0W\0i\0l\0s\0o\0n\0.\0p\0n\0g\0\0\0\n\0t\0\x61\0\x62\0l\0\x65\0\0\0\n\xff\xff\xff\xff)
You can replace the default (global) image located at $ANDROID_SDK_HOME/emulator/resources/poster.png with your poster.png image,
nor change the default pointer by editing the file $ANDROID_SDK_HOME/emulator/resources/Toren1BD.posters.
You can set the virtual scene image to a specified path. And manipulate the target image while testing.
As the Instrumented tests are running on your (virtual) device, it cannot manipulate the host machine files directly. What can be done, (which is an ugly hack) is to start a server on the host, which can be reached from the virtual device with the hosts loop-back "10.0.2.2" address.
This server can manipulate the target files.
If anybody has better solution, please share it!
An example server and client is here.
Server:
import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;
public class FileManipulatorServer {
public static void main(String args[]) {
int port = 6789;
FileManipulatorServer server = new FileManipulatorServer( port );
server.startServer();
}
// declare a server socket and a client socket for the server
private ServerSocket fileManipulatorServer = null;
private Socket clientSocket = null;
private int port;
public FileManipulatorServer(int port ) {
this.port = port;
}
public void stopServer() {
System.out.println( "Server cleaning up." );
System.exit(0);
}
public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
try {
fileManipulatorServer = new ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}
System.out.println( "Waiting for connections. Only one connection is allowed." );
// Create a socket object from the ServerSocket to listen and accept connections.
// Use FileManipulatorTask to process the connection.
while ( true ) {
try {
clientSocket = fileManipulatorServer.accept();
FileManipulatorTask task = new FileManipulatorTask(clientSocket, this);
task.run();
}
catch (IOException e) {
System.out.println(e);
}
}
}
}
class FileManipulatorTask {
private BufferedReader is;
private PrintStream os;
private Socket clientSocket;
private FileManipulatorServer server;
public FileManipulatorTask(Socket clientSocket, FileManipulatorServer server) {
this.clientSocket = clientSocket;
this.server = server;
System.out.println( "Connection established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop = false;
line = is.readLine();
System.out.println( "Received " + line );
saveImageToPoster(line.trim());
os.println("OK");
os.flush();
System.out.println( "Connection closed." );
is.close();
os.close();
clientSocket.close();
if ( serverStop ) server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
private void saveImageToPoster(String filename) {
try {
FileChannel src = new FileInputStream("C:\\fullpathtopostercandidates\\"+filename).getChannel();
FileChannel dest = new FileOutputStream("C:\\fullpathtoconfiguredposter\\poster.jpg").getChannel();
dest.transferFrom(src, 0, src.size());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.*;
import java.net.*;
public class FileNameSenderClient {
private String hostname = "10.0.2.2";
private int port = 6789;
public void sendFileName(String filename) {
Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;
try {
clientSocket = new Socket(hostname, port);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}
if (clientSocket == null || os == null || is == null) {
System.err.println( "Something is wrong. One variable is null." );
return;
}
try {
System.out.println("Write to output stream");
os.writeBytes( filename +"\n");
os.flush();
String responseLine = is.readLine();
System.out.println("Server returns: " + responseLine);
os.close();
is.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
Use the FileNameSenderClient from your instrumented test like this.
#Test
public void testQRcodeReadingOK()
{
FileNameSenderClient c = new FileNameSenderClient();
c.sendFileName("QRCode.jpg");
//your code that wants to use the image, like the this:
onView(withId(R.id.load_qr_code)).perform(click());
}

Android WiFi Direct client socket timeout

I'm new to Android, somewhat new to socket programming. I have two devices, running Android 5.1, connected with WiFi direct (not sure if that's relevant). I have a service where the server listens for a request on a socket, then returns a reply back to the client.
Likewise the client code sends a request and listens for the reply from the server. The server is sending the response, but the client never gets the message and the socket times out.
Server test code:
while (true) {
try {
Log.i(TAG, "test waiting for a request");
mServer = new ServerSocket(PORT);
Socket socket = mServer.accept(); //Block to receive message //
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i(TAG, "Message received! " + in.readLine());
String msg = "This is my reply.";
OutputStream outputStream = socket.getOutputStream();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(msg);
out.flush();
out.close();
} catch (SocketException e) {
Log.e(TAG, "Socket Accept Interrupted", e);
} catch (IOException e) {
Log.e(TAG, "Socket Failure", e);
} finally {
if (mServer != null && mServer.isBound()) {
try {
mServer.close();
} catch (IOException ioException) {
Log.e(TAG, "Failed to close socket trying to recover from SocketException", ioException);
}
}
}
}
Client test code:
Socket socket = null;
SocketAddress addr = new InetSocketAddress(host, PORT);
int socketTOms = 5000;
try {
socket = new Socket(host, PORT);
socket.setKeepAlive(false);
String syncReq = "Request to server.";
//Send Request//
OutputStream outputStream = socket.getOutputStream();
outputStream.write(syncReq.getBytes());
socket.setSoTimeout(socketTOms);
//Rcv reply//
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i(TAG, "Message received! " + in.readLine());
} catch (SocketTimeoutException e) {
Log.e(TAG, "Timeout while reading from socket: timeout=" + socketTOms);
} catch (Exception e) {
Log.e(TAG, "Exception", e);
} finally {
if (socket != null && socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Exception while closing socket", e);
}
}
}
I'm running the server and client on two different devices through Android Studio and can see in the logs that the server receives the request and sends the reply, but the client always throws SocketTimeoutException. I saw else where that socket.setKeepAlive(false) would fix the problem, but it doesn't seem to have any effect.
Seems simple enough, but I can't see what I'm missing here.
May be try this line of code before infinite loop mServer = new ServerSocket(PORT);
Did you try to create thread in sever side app. This makes the process to run in parallel so that while server is waiting for request the application does not gets hang. First of all try this code for localhost . To find Inetaddress just use InetAddress.getLocalHost(). Then run this. For communication with different devices there is service provided that is called (NSD) (Network Service Discovary).
But if you want to run this way I have written a code for you.
Server side code
TextView textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
connect();
}
}
);
}
public void connect()
{
MyServer myServer= new MyServer();
myServer.setEventListener(this);
myServer.startListening();
}
#Override
public void Display(String message) {
textView.setText("Client - "+ message);
}
}
Client side code
TextView textView;
Button button;
Thread mThread;
Socket clientSocket;
Button sendBtn;
public String userText1;
ObjectOutputStream output;
EditText editText;
Object userText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
button=(Button)findViewById(R.id.button);
sendBtn=(Button)findViewById(R.id.sendBtn);
editText=(EditText)findViewById(R.id.editText);
sendBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
userText=editText.getText().toString();
start();
}
}
);
public void start()
{
mThread= new Thread(new Runnable() {
#Override
public void run() {
try {
clientSocket = new Socket("127.0.0.1", 2001);
Log.v("binaya", "client socket created");
output = new ObjectOutputStream(clientSocket.getOutputStream());
output.writeObject(userText);
Message serverObj = Message.obtain();
ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
String strMsg = input.readObject().toString();
serverObj.obj = strMsg;
mHandler.sendMessage(serverObj);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
mThread.start();
}
Handler mHandler= new Handler()
{
#Override
public void handleMessage(Message msg) {
msgDisplay(msg.obj.toString());
}
};
private void msgDisplay(String msg) {
textView.setText("Server - " + msg);
}
We have used handler because we cannot touch user interface from inside runnable in this case.
Thanks
Figured this out ....
On the client side I was using outputStream.write(...) to send the request to the server as in:
String syncReq = "Request to server.";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(syncReq.getBytes());
But reading it on the server with BufferedReader.readLine():
Socket socket = mServer.accept(); //Block to receive message //
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i(TAG, "Message received! " + in.readLine());
My problem was that outputStream.write(...) does not append a '\n' at the end of the String, but in.readLine() on the server expects it. Therefore the server was blocking while waiting for '\n'; which in turn caused the client socket to timeout.

Getting socket timeout when receiving frequent requests at once

I attempting to build a remote controller for my laptop using my phone.
I written a server application that running on my laptop, the remote app used as a client to the server application.
I want to implement a mouse pad, the problem is when I am moving my finger over the "touch pad" too fast, I am receiving read time out on server side after few iterations.
Server code
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(20);
Runnable serverTask = new Runnable()
{
#Override
public void run()
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(DEFAULT_PORT);
serverSocket.setReuseAddress(true);
_working = true;
while (_working)
{
Socket clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(10000);
clientProcessingPool.submit(new ClientTask(clientSocket));
}
}
catch (IOException e)
{
System.err.println("Unable to process client request");
e.printStackTrace();
}
finally
{
try
{
if (serverSocket != null)
{
serverSocket.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
private class ClientTask implements Runnable
{
private final Socket clientSocket;
private ClientTask(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
#Override
public void run()
{
System.out.println("Got a client !");
try
{
System.out.println("Connected!");
DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());
String request = dIn.readUTF();
parseRequest(request);
System.out.println("request=" + request);
dOut.writeUTF("Got the command");
dOut.flush(); // Send off the data
dIn.close();
dOut.close();
clientSocket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
I thought maybe I will send the requests only if the distance from the starting position to end position is bigger than STEPS(a constant) and only then send the request. But I think the mouse won`t move fluidly.
Thanks.
RXAndroid and RXJava are perfect for asynchronously handling these request and will allow you to add a debounce to the frequent requests. Check out Reactive.io

How to send a message from Android to Windows using USB

I am a complete noob at Android, only at the level of basic (1 or 2 line) Activities activated by buttons, but I would like to create a really simple app that, when I tap the app icon, it fires and forgets a message to a listening server on my Windows 8 PC. The phone is connected as a simple media device, without Kies, via a USB cable.
I can get as far as a message box lying and saying the message was sent. I need to know what kind of comms channel to use, e.g. a COM port or what, and how to send data over that from Android. On the Windows side, once I've established how to communicate, I can help myself.
starting with the desktop side of this application:
You can use the ADB (Android debug bridge) to establish a tcp/ip socket connection via port between the device and desktop. The command is :
adb forward tcp:<port-number> tcp:<port-number>
to run this command in your java program, you will have to create a process builder wherein this command ets executed on a child shell.
For windows you may need to use:
process=Runtime.getRuntime().exec("D:\\Android\\adt-bundle-windows-x86_64-20130729\\sdk\\platform-tools\\adb.exe forward tcp:38300 tcp:38300");
sc = new Scanner(process.getErrorStream());
if (sc.hasNext())
{
while (sc.hasNext())
System.out.print(sc.next()+" ");
System.out.println("\nCannot start the Android debug bridge");
}
sc.close();
}
The function required to execute adb commands :
String[] commands = new String[]{"/bin/sh","-c", command};
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String s = null;
while ((s = stdInput.readLine()) != null)
{
sb.append(s);
sb.append("\n");
}
while ((s = stdError.readLine()) != null)
{
sb.append(s);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
Above method will take the above command as a string and execute it on a child shell
//Extracting Device Id through ADB
device_list=CommandExecutor.execute("adb devices").split("\\r?\\n");
System.out.println(device_list);
if(device_list.length>1)
{
if(device_list[1].matches(".*\\d.*"))
{
device_id=device_list[1].split("\\s+");
device_name=""+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.manufacturer")+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.model");
device_name=device_name.replaceAll("\\s+"," ");
System.out.println("\n"+device_name+" : "+device_id[0]);
device=device_id[0];
System.out.println("\n"+device);
}
else
{
System.out.println("Please attach a device");
}
}
else
{
System.out.println("Please attach a device");
}
CommandExecutor is a class which has the execute method in it. The code of the execute method is the same as posted above.
This will check if any device is connected and if it connected, it will return it unique id number.
It is preferable to use id number while executing adb commands like :
adb -s "+device_id[0]+" shell getprop ro.product.manufacturer
OR
adb -s <put-id-here> shell getprop ro.product.manufacturer
Note that '-s' is necesarry after adb.
Then using adb forward commnd you need to establish a tcp/ip socket. Here the desktop will be the client and mobile/device will be the server.
//Create socket connection
try{
socket = new Socket("localhost", 38300);
System.out.println("Socket Created");
out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hey Server!\n");
new Thread(readFromServer).start();
Thread closeSocketOnShutdown = new Thread() {
public void run() {
try {
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
Runtime.getRuntime().addShutdownHook(closeSocketOnShutdown);
}
catch (UnknownHostException e) {
System.out.println("Socket connection problem (Unknown host)"+e.getStackTrace());
} catch (IOException e) {
System.out.println("Could not initialize I/O on socket "+e.getStackTrace());
}
Then you need read from the server i.e. the device :
private Runnable readFromServer = new Runnable() {
#Override
public void run() {
try {
System.out.println("Reading From Server");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((buffer=in.readLine())!=null) {
System.out.println(buffer);
}catch (IOException e) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
The 'buffer' will contain what device will send from its end of the app.
Now in your mobile application,you will need to open the same connection and siple write data to it out buffer
public class TcpConnection implements Runnable {
public static final int TIMEOUT=10;
private String connectionStatus=null;
private Handler mHandler;
private ServerSocket server=null;
private Context context;
private Socket client=null;
private String line="";
BufferedReader socketIn;
PrintWriter socketOut;
public TcpConnection(Context c) {
// TODO Auto-generated constructor stub
context=c;
mHandler=new Handler();
}
#Override
public void run() {
// TODO Auto-generated method stub
// initialize server socket
try {
server = new ServerSocket(38300);
server.setSoTimeout(TIMEOUT*1000);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//attempt to accept a connection
try{
client = server.accept();
socketOut = new PrintWriter(client.getOutputStream(), true);
socketOut.println("Hey Client!\n");
socketOut.flush();
syncContacts();
Thread readThread = new Thread(readFromClient);
readThread.setPriority(Thread.MAX_PRIORITY);
readThread.start();
Log.e(TAG, "Sent");
}
catch (SocketTimeoutException e) {
// print out TIMEOUT
connectionStatus="Connection has timed out! Please try again";
mHandler.post(showConnectionStatus);
try {
server.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
catch (IOException e) {
Log.e(TAG, ""+e);
}
if (client!=null) {
try{
// print out success
connectionStatus="Connection succesful!";
Log.e(TAG, connectionStatus);
mHandler.post(showConnectionStatus);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
private Runnable readFromClient = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Log.e(TAG, "Reading from server");
socketIn=new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = socketIn.readLine()) != null) {
Log.d("ServerActivity", line);
//Do something with line
}
socketIn.close();
closeAll();
Log.e(TAG, "OUT OF WHILE");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void closeAll() {
// TODO Auto-generated method stub
try {
Log.e(TAG, "Closing All");
socketOut.close();
client.close();
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Runnable showConnectionStatus = new Runnable() {
public void run() {
try
{
Toast.makeText(context, connectionStatus, Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
}
}
Using Managed.adb in c#
AndroidDebugBridge bridge = AndroidDebugBridge.
CreateBridge(#"C:\Users\bla\AppData\Local\Android\Sdk\platform-tools\adb.exe", true);
List<Device> devices = AdbHelper.Instance.
GetDevices(AndroidDebugBridge.SocketAddress);
devices[0].CreateForward(38300, 38300);
Then create a server socket on android to that port.
server = new ServerSocket(38300);
server.setSoTimeout(TIMEOUT * 1000);
socket = server.accept();
and client socket on C#
TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect("127.0.0.1", 38300);

ServerSocket Android

Hey community I have the following ServerSocket which should listen to port 53000 and log any received data. However, I cannot seem to get past the server.accept() blocking call.
public void run() {
SocketServer server = new ServerSocket(53000);
//---buffer store for the stream---
byte[] buffer = new byte[1024];
//---bytes returned from read()---
int bytes;
//---keep listening to the InputStream until an
// exception occurs---
while (true) {
try {
socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Log.i("received response from server", str);
in.close();
socket.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e){
server.close();
Log.e(TAG, e.getMessage());
}
}
}
I have also given the application the INTERNET permission in the Manifest file.
()
To add to the mystery, I have also verified client responses get sent to that port.
Is there something in particular I need to do to make this work?
Thanks.
Your code is very messy and won't even compile. I made some adjustments so that i could test your code, and it's working fine. Here is the test application I used:
package com.test.stackoverflow
import java.io.BufferedReader;
public class ServerSocketTestActivity extends Activity {
/** Called when the activity is first created. */
private static String TAG = "ServerSocketTest";
private ServerSocket server;
Runnable conn = new Runnable() {
public void run() {
try {
server = new ServerSocket(53000);
while (true) {
Socket socket = server.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Log.i("received response from server", str);
in.close();
socket.close();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(conn).start();
}
#Override
protected void onPause() {
super.onPause();
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Using this code and netcat running via adb shell I was able to connect and communicate with the application.
When working with The Client Declare these methods
To access Streams
// gets the input stream // ObjectInputStream input;
// gets the output stream // ObjectOutputStream output;
// ServerSocket server;
// Socket connection;
maybe you have a another class to access the socket;
server = new ServerSocket(5001, 100);
// step 1 create socket connection
server = new ServerSocket(5001, 100);
while(the condition is true)
// step 2 wait for connection
// step 3 get streams
// step 4 : process the connection
// step 5 : close connection

Categories

Resources