I am developing an Android Application, and application needs to connect server.
This is the client code. 79.123.176.59 is the server's IP address. Application and the server are connected to same network. When I execute my application, it never opens a socket. So it cannot connect to server.
When I execute client code seperate from the application, it just works fine!
What is the problem ? Do you have any suggestions ?
Thank you!
int port=8080;
Socket s;
String msg="";
String err="error";
try{
Log.d("Client","Socket");
s=new Socket("79.123.176.59",port);
Log.d("Client","Socket opened");
OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream());
PrintWriter pw=new PrintWriter(osw);
BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream()));
Log.d("Client","Streams");
pw.println(latitude + " " + longitude );
Log.d("Client","String send");
pw.flush();
msg=br1.readLine();
return msg;
}
catch ( Exception e )
{
return err;
}
You are not closing the socket neither the streams. So maybe you cannot connect because your device is blocked by a socket you opened before.
Try to put this after your catch (and dont do return inside try/catch)
finally {
pw.close();
br1.close();
s.close();
}
TCP SOCKET on Android You can follow this thread and the code is also available there.
The Socket constructor does not take a string, I don't get how that even compiles?
Try this
s=new Socket(new InetAddress.getByName("79.123.176.59"),port)
Related
I am using Tcp Sockets For Communication Between CLR C++ (Server) to Android(Client) While using .Net For GUI.
While the data is communicated and received. Using a Background Worker in C++ Application
if(backgroundworker1->CancellationPending)
{
listenerSocket->Close(); // Listener Socket is Closed
netStream->Close();
serverSocket->Close();
serverSocket->Shutdown(SocketShutdown::Both);
e->Cancel;
break;
}
While in Android i am using Async Class for Execution and receiving text from socket to a Handler. While in Doinbackground Function i am using this code.
try
{
socket = new Socket(dstAddress, dstPort);
BufferedReader inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
do
{
try
{
if (!inputStream.ready())
{
if (message != null)
{
MainActivity.handler.obtainMessage(0, 0, -1,"Server: " + message).sendToTarget();
message = "";
}
}
int num = inputStream.read();
message += Character.toString((char) num);
Log.e(message,message);
}
catch (Exception classNot)
{
Log.e("Client TASK","classnot exception");
}
}
while (!message.equals("bye"));
inputStream.close();
socket.close();
}
I don't understand While am sending the Bye Message from the server and (Backgroundworker1->CancellationPending)
All server sockets are closed and Mobile Sockets are closed why is the UI Not Responding? Please Help..
The Problem was in Client in doinbackground Which calls the while loop again hence causing an exception because no data was received in the sockets and causing an exception. Finally added some sleep to the client that after some time the client query the server while if there is no message from the server the client shutdowns and shifted to postexecution function.
I am trying to connect a simple android client to a simple java server on another computer running on the same wi-fi network, i was able to connect with a java code(non android) on eclipse, and the server works just fine, but when i take the same code and put in my android app (android studio), it throws an IOException.
As of right now my protocol just returns a string "yay" and i just want to display it in a View.
My code:
private void createCom2(TextView showResult){
Socket pazeSocket = null;
PrintWriter pw = null;
BufferedReader br = null;
String ip = "10.0.0.4";
try {
pazeSocket = new Socket(ip, 4444);
pw = new PrintWriter(pazeSocket.getOutputStream());
br = new BufferedReader(new InputStreamReader(pazeSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(this,"Don't know about host: " + ip , Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this,"Couldn't get I/O for the connection to: " + ip , Toast.LENGTH_SHORT).show();
}
}
Thanks.
You need Internet permission for your app. Add this line to your manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
and read more abut permissions here, if you like:
http://developer.android.com/guide/topics/manifest/manifest-intro.html
I am trying to send data from my Android phone to my home-server by using sockets. My server runs Linux so I used Perl to code the script for my server. The connection works fine and I can send data to my client running on the phone.
Problem is, when I send something (first try was a simple string) to the server, I don't receive anything at the servers side. Everything works fine if I use telnet to send a string to the server.
I am sitting here for some time now and I looked if there was a similar question to mine and could not find any in which the problem is discussed for Android to Perl-script. Here is my code for the Android app:
try {
Socket socket = new Socket("192.168.178.22", 22222);
Statusinformation("connection with server succeed");
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Statusinformation(input.readLine());
OutputStream outstream =socket.getOutputStream();
PrintWriter out = new PrintWriter(outstream);
out.println("This is a test message from client on phone!\n");
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Statusinformation("connection unsucsessfull");
e.printStackTrace();
}
on my phone I receive this if i execute the above code:
connection with server succeed!
and on the server side I'm using this code to receive the string from socket clients:
use IO::Socket;
my $server = IO::Socket::INET -> new(
Proto => 'tcp',
LocalPort => 22222,
Listen => SOMAXCONN,
);
print "Server started..\n";
while (1) {
next unless my $conect = $server -> accept();
my $childconection = fork;
if ($childconection == 0) {
handle_connection($conect);
}
}
sub handle_connection
{
my $sock = shift;
my $client_message="";
my $client_addr = $sock -> peerhost;
print "connection: $client_addr connected\n";
print $sock "hi $client_addr, you are connected!\n";
while (1) {
open (Tempfile, '>>tempfile.txt');
while ($client_message = <$sock>) {
print Tempfile $client_message;
print $client_message;
}
close (Tempfile);
}
close($sock);
exit(0);
}
ok now I am a little ashamed.
I solved the problem by adding:
out.flush();
the flush() method assures that all pending data is send to the target and flushs the target.
I've been trying to implement a simple socket communication between two Android emulators but just can't seem to get it.
My server:
public void run() {
if (SERVERIP != null) {
try {
serverStatus.setText("My IP: " + SERVERIP);
serverSocket = new ServerSocket(6798);
serverStatus.setText("ServerSocket Created");
}
catch(Exception e) {
e.printStackTrace();
}
try {
while (true) {
serverStatus.setText("waiting for client");
Socket client = serverSocket.accept();
serverStatus.setText("Connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = in.readLine();
serverStatus.setText(line);
in.close();
client.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}
else
serverStatus.setText("Couldn't detect internet connection.");
}
My Client:
try {
InetAddress ina = InetAddress.getByName("10.0.2.2");
socket = new Socket(ina, 6789);
}
catch (Exception e) {
e.printStackTrace();
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Hey Server!");
dispText.setText("sent");
}
catch (Exception e) {
e.printStackTrace();
}
The Client side goes on to display the message "sent" however the Server does not move beyond "waiting for client" (stuck on the blocking accept()).
I've used telnet on my Windows machine to redirect port 6789 to 6798 on the server emulator's console. I've also tried turning off my firewall and the other suggestions posted on the similar questions asked here. Please help as just can't seem to get it and feel like I'm making a very stupid mistake.
Also, can anyone please tell me how it is possible for the Client to move beyond the Socket creation code line if the Server is still stuck on accept(). Or, does it not matter to the client that the Server isn't responding as long as it is listening on the port??
Android emulators are placed behind a virtual firewall/router by design, and cannot see each other, even when they are on the same network. The "Using Network Redirection", as well as "Interconnecting Emulator Instances" part of Google's doc on the emulator explains how to communicate with an emulator instance.
As for your last question. Use the empty constructor for socket, and then use the connect call with a specified timeout.
Im trying to send a command through telnet to my computer which then sends the command to a serial port, when using telnet using
adb shell
$telnet 172.20.104.203 5334
$h
it returns the data from the command h, how ever when I try to do this using android it connects to the socket, I can see this on the computer, it sends the command but then as soon as it logs that it has sent it hangs and comes up with "Application not responding" and it has wait or force close and if I wait it just stays the same.
This is my code for the telnet part
private static final int TCP_SERVER_PORT = 5334;
private void runTcpClient() {
try {
Socket s = new Socket("172.20.104.203", TCP_SERVER_PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//send output msg
String outMsg = "$getPos";
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
//accept server response
String inMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpClient", "received: " + inMsg);
//close connection
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
It logs the send, but it never logs the receive, I thought it might be something to do with the amount of data being received so I just sent
$getPos
instead but it still hangs.
Any one know what could be happening?
I'm not familiar with the particulars of the platform, but its unlikely that a readline will work on a socket/tcp stream, or if it works, it will work unreliably. Data coming in from a socket is not necessarily organized into 'lines', but instead packets of a particular size. A 'read' performed on a socket will return some number of bytes.
The client doing such reads needs to read each packet, buffer them until it receives an agreed-upon 'end of data' marker. The marker agreed-upon is determined by protocol.
You've shown us the client side of your code. Do you have a corresponding server side?
From what you have here, my guess is that your client code is waiting patiently for an 'end of line' that for some reason, will never come. OR there's something wrong at the server end and the server isn't sending any data to the client.