i'm new in Android. I have the following code:
public class SettingsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tcp_settings);
Button buttonConnect = (Button) findViewById(R.id.buttonConnect);
buttonConnect.setOnClickListener(new View.OnClickListener() {
EditText server_ip = (EditText) findViewById(R.id.set_server_ip);
EditText port = (EditText) findViewById(R.id.set_port);
#Override
public void onClick(View view) {
String serverAddr = server_ip.getText().toString();
String serverPort = port.getText().toString();
new connectTask().execute(serverAddr, serverPort);
}
});
}
class connectTask extends AsyncTask<String, Void, String> {
Socket socket;
#Override
protected String doInBackground(String... params) {
int servport = Integer.parseInt(params[1]);
try {
socket = new Socket(params[0], servport);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return params[0] + " : " + params[1];
}
}
}
I want to set a socket with server ip and port getting from EditTexts server_ip and port. In the connectTask I make a conversion from string to int in: int servport but i'm still getting error:
Caused by: java.lang.NumberFormatException: Invalid int "".
i have to make serverAddr to String because i have to put it in :
new connectTask().execute(serverAddr, serverPort);
But then socket require port as Int so conversion is required.
Could You help me and tell what i'm doing wrong ?
Your problem lies here within your code. You are passing in multiple parameters into a function that only receives one. Here is the def of execute: execute (Params... params)
new connectTask().execute(serverAddr, serverPort);
Change line to this:
new connectTask().execute(new String[]{serverAddr,serverPort});
Although the documentation does not say it, it is wanting an array of the first template object being passed in IF you are passing in more than one parameter.
Related
I want to send and receive messages from my socket server which is created in python on windows with the help of twisted API. My client is going to be my android phone through I am going send my string messages. Here is my code. can someone please help out.
public class MainActivity extends AppCompatActivity
{
//TextView textView;
Button sendButton;
Button connect;
EditText message;
OutputStream outputStream;
InputStream inputStream;
Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendButton = (Button) findViewById(R.id.sendButton);
connect = (Button) findViewById(R.id.button);
message = (EditText) findViewById(R.id.message);
connect.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
connect.setText("Disconnect");
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects)
{
try {
socket = new Socket("192.168.100.106",8888);
try {
outputStream = socket.getOutputStream();
inputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
connect.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
sendButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view)
{
PrintWriter out = new PrintWriter(outputStream);
String mes = message.getText().toString();
out.print(mes);
}
});
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
asyncTask.execute();
}
});
}
}
And here is my socket server script coded in python with the help of twisted API.
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
import ctypes # An included library with Python install.
class DataTransfer(Protocol):
def connectionMade(self):
#self.transport.write("""connected""")
self.factory.clients.append(self)
print "clients are ", self.factory.clients
self.username = ""
self.password = ""
self.auth = False
self.ipaddress = self.transport.getPeer()
print self.ipaddress
def connectionLost(self, reason):
self.factory.clients.remove(self)
print reason
def dataReceived(self, data):
print data
a = data.split(':')
if len(a) > 1:
command = a[0]
content = a[1]
msg = ""
self.message(msg)
def message(self, message):
self.transport.write(message + '\n')
factory = Factory()
factory.protocol = DataTransfer
factory.clients = []
reactor.listenTCP(8888, factory)
print "Server started"
reactor.run()
Presently I am able to communicate (ie. connect and disconnect with the server.) but its just that I am not able to send and receive messages.
Instead of PrintWriter out = new PrintWriter(outputStream); directly use the outputStream and it should work. :)
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()
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.
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.
I want to develop app that connect to a server and send and receive message. i'm really beginner in that.
So,i wrote this code by This tutorial, and it seem that i get some mistake with the port or ip address beacuse i didn't get the message to the console. My inspiration is the problem is in my router setting maybe
Here is my android code (Project android)
public class MainActivity extends Activity {
Socket client;
PrintWriter printWriter;
EditText edIp,edPort,edMess;
String message;
int port = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edIp = (EditText) findViewById(R.id.edIp);
edPort = (EditText) findViewById(R.id.edPort);
edMess= (EditText) findViewById(R.id.edMessage);
edIp.setText("10.0.2.2");
edPort.setText("4444");
}
public void onClick(View v){
message = edMess.getText().toString();
edMess.setText("");
port = Integer.parseInt(edPort.getText().toString());
new Thread(new Runnable() {
#Override
public void run() {
try {
client = new Socket(edIp.getText().toString(),port);
printWriter = new PrintWriter(client.getOutputStream());
printWriter.write(message);
printWriter.flush();
printWriter.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}).start();
}
}
(java aplication)
public class Main {
public static void main(String[] args) throws IOException {
Socket clientSocket = null;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
System.out.println("Server started...");
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("error" + e);
}
Scanner in1 = new Scanner(clientSocket.getInputStream());
String mess;
while (true) {
if(in1.hasNext()){
mess = in1.nextLine();
System.out.println("Client message : "+mess);
}
}
}
}
I am working on a basic client-server application to send messages between an android app (client) and a java server on the pc. The messages are being sent and received fine when I use the emulator but does not work when i try to use the app on my mobile. I connect my phone to a wifi network hosted by my laptop using connectify. I wonder whats preventing my phone from connecting...
Here is the code :
SERVER
public class ServerMain {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
int sock = 1234;
ServerSocket welcomeSocket = new ServerSocket(sock);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
if(clientSentence.equalsIgnoreCase("QUIT"))
break;
}
welcomeSocket.close();
}
}
CLIENT
public class Message extends Activity {
EditText et;
String msg1 = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et = (EditText)findViewById(R.id.etTest);
}
// TODO Auto-generated method stub
class GetMessages extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
final String msg = et.getText().toString();
try{
Socket clientSocket = new Socket("*myip*", 1234);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
String sentence = msg;
outToServer.writeBytes(sentence + '\n');
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
public void readWebpage(View view) { //The button on click calls this function (from xml)
new GetMessages().execute();
}
}
the following is my code. Editor: Eclipse, Platform: Windows.
Its a chat application where 2 android emulators connect through a tcp socket.
UI consists of a send button, a text view and a text box.
Problem: As soon as I type text and hit send, the application crashes.
server port is 8000.
So my redirection is redir add tcp:8081:8000 and redir add tcp:8082:8000.
I donno what is wrong in my code. Please suggest me somthing I need to change.
public class HelloandroidActivity extends Activity
{
/** Called when the activity is first created. */
public int serverport=8000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText nameField = (EditText) findViewById(R.id.editText1);
final Button button2 = (Button) findViewById(R.id.button1);
Integer severport=8000;
new Server().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,severport);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final String name = nameField.getText().toString();
final TextView tv = (TextView) findViewById(R.id.textView1);
//tv.setText(name);
String s=null;
new Client().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,s);
}
});// end onclicklis
}//end oncreate
class Server extends AsyncTask <Integer, String, String>
{
public InetAddress byIpAsName ;
int r=0;
#Override
protected String doInBackground(Integer... serverport) {
//i[0]=serverport;
Integer[] sp=serverport;
BufferedReader in=null;
ServerSocket s=null;
r=sp[0];
String cIn="";
try {
//byIpAsName = InetAddress.getByName("10.2.2.15");
s=new ServerSocket(r);
while(true)
{
Socket client = s.accept();
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line=in.readLine();
cIn=null;
while(line!=null){cIn=cIn.concat(line);}
}//while
} catch (IOException e) {
e.printStackTrace();
}
try {
s.close();
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
return cIn;
}//end inBackground
//#SuppressWarnings("null")
protected void onPostExecute(String... cIn)
{
}//onpost execute
}//server class
public class Client extends AsyncTask<String, String, String>
{
PrintWriter out = null;
BufferedReader in=null;
String sIn=null;
//Server s1=new Server();
//int q=s1.r;
TelephonyManager tel = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() - 4);
int q = Integer.parseInt(portStr);
Socket socket;
#Override
protected String doInBackground(String... params) {
try
{
//q=8080;
InetAddress byIpAsName1=InetAddress.getByName("10.0.2.2");
socket = new Socket(byIpAsName1, q);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line=in.readLine();
sIn=null;
while(line!=null){sIn=sIn.concat(line);}
}
catch (IOException e) {
e.printStackTrace();
}//catch
return sIn;
}//in background
protected void onPostExecute(String... sIn)
{
String c=null;
final TextView tv = (TextView) findViewById(R.id.textView1);
c=c.concat(sIn[0]);
tv.setText(c);
}
}
}//main class
From your logcat, what is important is this line:
03-16 23:12:23.434: E/AndroidRuntime(571): java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10040 nor current process has android.permission.READ_PHONE_STATE.
This indicates that in order to run your code, you need the READ_PHONE_STATE permission in the android manifest.xml.
Add this line to the manifest, outside of the <application> tag but inside the <manifest> tag.
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
If this does not solve the issue, the problem could be related to this answer.