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()