0

I am trying to write an app that sends a string to a specified IP address and Port number. The destination already has a server that accepts strings, but for some reason, the app cannot establish a socket with the server, it keeps timing out. I have only written code, so if I have to do something else like port forward on either the client or server end, please let me know.

The goal of this app is to take in a string for an IP address, a string for the Port number, and a String for the message to send to the destination. After pressing the Send button, the app will send the message to the IP and Port number defined, and display a response from the server.

This also will be used in two applications: once between the Android App and a Python server, and other between the Android App and custom hardware. Hopefully there is a solution to fit both cases.

Client Code:

public static class PlaceholderFragment extends Fragment {

        TextView recieve;
        EditText addressText, portText, messageText;
        Button send;

        Socket socket = null;

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(
                    R.layout.fragment_customize_gateway, container, false);

            recieve = (TextView) rootView.findViewById(R.id.textView1);
            addressText = (EditText) rootView.findViewById(R.id.editText1);
            portText = (EditText) rootView.findViewById(R.id.editText2);
            messageText = (EditText) rootView.findViewById(R.id.editText3);

            send = (Button) rootView.findViewById(R.id.send);
            send.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    AsyncSend aSend= new AsyncSend(addressText.getText().toString(),Integer.parseInt(portText.getText().toString()), messageText.getText().toString());
                    aSend.execute();
                }
            });
            return rootView;
        }

        public class AsyncSend extends AsyncTask<Void, Void, Void> {
            String address;
            int port;
            String message;
            String response;
            AsyncSend(String addr, int p, String mes) {
                address = addr;
                port = p;
                message = mes;
            }

            @Override
            protected Void doInBackground(Void... params) {
                android.os.Debug.waitForDebugger();
                Socket socket = null;
                try {
                    System.out.println("Test");
                    socket = new Socket(address, port);
                    System.out.println("Test");
                    DataOutputStream writeOut = new DataOutputStream(socket.getOutputStream());
                    writeOut.writeUTF(message);
                    writeOut.flush();


                    ByteArrayOutputStream writeBuffer = new ByteArrayOutputStream(1024);
                    byte[] buffer = new byte[1024];

                    int bytesRead;
                    InputStream writeIn = socket.getInputStream();

                    while((bytesRead = writeIn.read(buffer)) != -1) {
                        writeBuffer.write(buffer,0,bytesRead);
                        response += writeBuffer.toString("UTF-8");
                    }
                } catch (UnknownHostException e){
                    e.printStackTrace();
                    response = "Unknown HostException: " + e.toString();
                    System.out.println(response);
                } catch (IOException e) {
                    response = "IOException: " + e.toString();
                    System.out.println(response);
                } finally {
                    if (socket != null) {
                        recieve.setText(response);
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                recieve.setText(response);
                super.onPostExecute(result);
            }
        }
    }

Server Code:

import http.server
import socket
import threading
import socketserver

import pymongo

import smtplib

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        #Connect to database
        try:
            from pymongo import MongoClient
            dbclient = MongoClient()
            db = dbclient.WDI_database
            print("Database Connected")
        except pymongo.errors.ConnectionFailure as e:
            print("Database Failed: {}".format(e))

        col = db.users

        data2 = str(self.request.recv(1024), 'ascii')
        print("Server: {}".format(data2));
        data = data2.split("||")
        username, password, camunits, homunits = data[0], data[1], data[2], data[3]
        post = {"user": username,
                "pass": password,
                "cam": camunits,
                "disp": homunits}
        col.insert(post)
        print(col.count())

        cur_thread = threading.current_thread()
        response = bytes("{} Received data for: {}".format(cur_thread, username), 'ascii')
        self.request.sendall(response)

class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]
        print("Recieved: " + data.decode("utf-8"))
        socket.sendto(data.upper(), self.client_address)

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = "", 5000

    tcpserver = ThreadedTCPServer((HOST, PORT-1), ThreadedTCPRequestHandler)
    server_thread = threading.Thread(target=tcpserver.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    print("TCP serving at port", PORT-1)

    while True:
        pass
    tcpserver.shutdown()

2 Answers 2

1

Using the Socket class is too low-level for your purposes and fraught with potential gotcha's. I suggest using org.apache.http.client.HttpClient instead.

Sign up to request clarification or add additional context in comments.

3 Comments

Can I keep the server the same, or do I have to recode the server too?
No, nothing needs to be changed on the server. As long as you're using HTTP protocol, HttpClient is for you!
Thank you for your suggestion, I will keep this in mind. There is another part of this project that I didn't mention: this client/server dynamic will also have to be mirrored but the server is a custom made piece of hardware that may not be able to handle HTTP connections, so I would like to have that connection as low or simple as possible.
0

It was probably because I didn't port forward, so my connection got blocked by my router. I opened the port on both the router and Windows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.