Reputation: 559
I am trying to connect android app(client) with java application(server 'PC') here is my client side code.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
txt = (EditText) findViewById(R.id.editText1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
new CallServer().execute();
}
});
}
public class CallServer extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... arg0) {
String modifiedSentence = "hello";
Socket clientSocket;
try {
clientSocket = new Socket("192.168.1.100", 8081);
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes("hello world");
modifiedSentence =
(inFromServer.readLine());
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return modifiedSentence;
}
protected void onPostExecute(String result) {
txt.setText(result);
}
}
Android permission
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
I cant find the problem with this code as it does not give any type of warring or error my server side code is perfectly working as I have tested it with other java application (client side). There isn't any kind of port issue as well because I have tested it by keeping client and server side code on different machines and it worked fine.
Upvotes: 1
Views: 2818
Reputation: 559
The issue was with my server side code. I didn't closed the BufferedReader so now it works fine.
Upvotes: 1
Reputation: 48272
You can not modify UI elements such as your txt
from doInBackground because it's a different thread.
Make doInBackground
return your socket data and set your txt
in onPostExecute
Upvotes: 1
Reputation: 13761
It's obvious it's not a router-firewall related problem as you are under the same net, so there are only a few possibilities:
You should make sure you can open that service some ther way, that would help you debugging where the culprit is. If you've already done this, I'd suggest using some debugging tool to trace TCP packets (I don't know either what kind of operating system you use on the destination machine; if it's some linux distribution, tcpdump
might help).
Upvotes: 1