I am trying to connect two android devices through Socket programming.Both the devices are in the same network so one will be acting as server and the other will be acting as client.
This is my server code:
public class WhiteServer extends AsyncTask<Integer,String,String> {
private View root;
public WhiteServer(View view){
root = view;
}
@Override
protected String doInBackground(Integer... params) {
try {
ServerSocket serverSocket = new ServerSocket(params[0]);
publishProgress("Sever is active on portNumber "+params[0]);
Socket s = serverSocket.accept();
publishProgress("Connected client is"+s.getRemoteSocketAddress());
} catch (IOException e) {
publishProgress(e.toString());
}
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(root.getContext(),"Done",Toast.LENGTH_LONG).show();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
TextView status = (TextView) root.findViewById(R.id.status);
status.setText(values[0]);
}
}
This is my client code:
public class Light extends AsyncTask<Integer,String,String> {
private String ipAddress;
private View view;
public Light(String ip,View v){
ipAddress = ip;
view = v;
}
@Override
protected String doInBackground(Integer... params) {
try{
Socket client = new Socket(ipAddress,params[0]);
publishProgress("Connected to server on port "+client.getLocalPort());
}catch (Exception e){
publishProgress(e.toString());
}
return "";
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Toast.makeText(view.getContext(),values[0],Toast.LENGTH_LONG).show();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(view.getContext(),"Done",Toast.LENGTH_LONG).show();
}
}
I registered the server in port 1028 and it is listening on port 1028. As both devices are connected same wifi HostName is same for both of them. When in server hostname and port(1028) is entered and clicked connect it says:
java.netConnectException : Connection refused
and also they are two different apps. Can I know how I solve this???