I am currently trying to open a socket in android, but my code keeps sticking at one sentence.
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void run(){
Log.i("DebugMessage", "ServerThread received pulse. Trying to open socket now!");
try{
serverSocket = new ServerSocket(25555);
Log.i("DebugMessage", "serverSocket is open, waiting for the clientSocket.");
clientSocket = serverSocket.accept();
Log.i("DebugMessage", "serverSocket and clientSocket are both open! Waiting for in-/output!");
in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
String input = in.readLine();
out.println("received: " + input);
in.close();
out.close();
} catch(Exception e) {
Log.i("DebugMessage", "Failed to open socket!");
e.printStackTrace();
}
}
At clientSocket = serverSocket.accept(); it keeps sticking.
Now I have seen this question a few other times, but the answers given were totally different.
Here is being said that it is about his code, and here is being said that the problem is with the emulator. Now my question is, is my problem with the emulator or my code, and if it is with my code, how is it possible to fix it?
By the way, I have added these lines to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
The answer of FD_ is correct but i want to clarify it a bit. accept() calls wait(). So the thread will wait for a connection.
You may want to call such code from a other thread.
ServerSocket.accept() waits until a device connects to the socket's port (25555 in your case) on your device's ip address. It will only proceed and return a Socket when there is a new connection.
You'll find more information in the docs.
Related
I have a wireless device communicating over port 22 connected to my network. Once the device starts up, it immediately starts sending log data. Once this device is sent a command, it stops logging and responds accordingly. This all works, I have tested it using a telnet client.
My problem is that I can't seem to send it a command properly in my app. I am reading the log data as planned, but when I send it a command, in this case the command "r", it continues outputting log data instead what it should be showing me for that particular command. This has to mean that I am not properly sending the command. This is my code for the task that sends it the command and logs the output in the android logcat:
public class ReceiveVarTask extends AsyncTask<Void, Void, Void>{
String dstAddress;
int Port;
ReceiveVarTask(String addr, int port) {
dstAddress = addr;
Port = port;
}
protected Void doInBackground(Void... vars){
Socket socket = null;
String command = "r";
try {
Log.i(TAG, "Connecting to port 22");
socket = new Socket(dstAddress, Port);
Log.i(TAG, "Connected to port 22");
PrintWriter writer = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
writer.println(command);
String line = reader.readLine();
Log.i(TAG, line);
while(line!=null && !isCancelled()){
line = reader.readLine();
Log.i(TAG, line);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
protected void onPostExecute(Void arg) {
taskRunning = false;
}
}
What am I doing wrong? Why is it not registering the command?
UPDATE:
I have used several telnet clients for testing, and the server is reading the 'r' command as expected on some. It works using a windows telnet client, and it works using the vSSH app by Velestar. Interestingly enough, when testing this with the android telnet client by ClockworkMod, the server is not registering the command either.
Could it be something to do with encoding?
Do I need any additional permissions to work with sockets? I have android.permission.INTERNET declared in the manifest.
UPDATE 2:
The developer of of the hardware just told me that the hardware is expecting the command to be ASCII encoded and CR terminated. So I will try changing PrintWrite initialization to:
PrintWriter writer = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream(), "ASCII")), true);
and the print command to:
writer.print(command+"\r");
Changing the the encoding type to "US-ASCII" and adding a carriage return instead of a new line did the trick. I'm able to read and write data as expected.
From my understanding of your problem description, you have a telnet server, and when a telnet client connects to that server, the server start sending the client log data. The client may send an "r" to the server to stop the log stream.
I suggest you first confirm using another telnet client that sending an "r" does stop the server from generating more log data.
You could use Wireshark to check if the "r" command is indeed sent.
I'm receiving an image through a socket in an android aplication, I did debugging and when I'm going to save the image in Drawable d, the program waits for something happens.
I think it has to have relation with clientSocket.getInputStream(); or with the socket.
I have a multithreading server in C++ and when I stop the server, the android aplication continues and I can see the image I sent before. But, I think it's not a server problem, because the socket in the server send the data and shows the message printf("Bytes enviados %d\n", bytesEnviados); which is at the end of the server code.
Here you have the code:
public Drawable mandaMensajeVideo(String mensaje, String ip, int puerto ) throws IOException{
Socket clientSocket = new Socket(ip, puerto);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(mensaje);
outToServer.flush();
InputStream inputStream = clientSocket.getInputStream();
Drawable d = Drawable.createFromStream(inputStream, null);
clientSocket.close();
outToServer.close();
return d;
}
Thanks!
Sounds like the end of the inputStream is never reached, as you never properly close the communication.
i am new to Android networking concepts.Now i am trying to connect my server and close the socket.after that i am create a new socket with old ip and port.It causes address already in use exception? can any one help me.below is my following code
Socket socket=new Socket("122.165.81.120",10200);
int port=socket.getLocalPort();
socket.shutdownInput();
socket.shutdownOutput();
try{
socket.close();
}catch(Exception e){
e.printStackTrace();
}
Socket socket2=new Socket();
SocketAddress myaddress = new InetSocketAddress("172.16.1.37",port);
socket2.bind(myaddress);
socket2.close();
You need to set the SO_REUSEADDR socket option. This is done with the Socket.setReuseAddr function.
I am writting simple program to connect server by socket in android.
But when i try to read data from socket's outputstream it will send automatically RST request. so my connection gets closed. but i want my connection to open always.
Please any one help me.
Thank you.
try {
Socket socket = new Socket("xxx.xxx.x.xx", 9083);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Testing");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String readObject = reader.readLine();
System.out.println(readObject);
} catch (Exception e) {
e.printStackTrace();
}
The most usual reason for 'connection reset' is that you have written to a connection that has already been closed by the other end. In other words, an application protocol error.
I have a server running on my computer and I would like my android app to connect to it. In other words, I would like to write an Android client that establishes a TCP connection, writes something to the server and listens for responses from the server. Below is the client code:
public class Text extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
String fromServer, ToServer, filename;
BufferedReader inFromServer;
PrintWriter outToServer;
Socket clientSocket;
super.onCreate(savedInstanceState);
try
{
clientSocket = new Socket("86.36.32.251", 8000);
outToServer = new PrintWriter(clientSocket.getOutputStream(),true);
inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
filename = "profile.txt";
ToServer = Reader.readFileAsString(filename);
ToServer += "\n";
outToServer.println(ToServer);
while((fromServer = inFromServer.readLine()) != null)
{
TextView tv = new TextView(this);
tv.setText(fromServer);
setContentView(tv);
}
inFromServer.close();
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
However, when I run my application, the application does not establish a TCP connection to my server. I don't know what the problem might be. I have gone through the following link http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/ which discusses the client-side of socket programming and I feel I have all the main steps in my client. Could someone please help me resolving the issue. Thanks
Please make sure you've added the internet permission.
If you did, run this on a real device.
If it still doesn't work, paste the logcat.