Hi I creating simple comminication serwer in Python 2.7, my first goal is to send "list" to android App with sockets.
import socket
import sys
HOST = '192.168.0.108' # this is your localhost
PORT = 8888
list=str(["firstitem",'nextitem'])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# socket.socket: must use to create a socket.
# socket.AF_INET: Address Format, Internet = IP Addresses.
# socket.SOCK_STREAM: two-way, connection-based byte streams.
print 'socket created'
# Bind socket to Host and Port
try:
s.bind((HOST, PORT))
except socket.error as err:
print 'Bind Failed, Error Code: ' + str(err[0]) + ', Message: ' + err[1]
sys.exit()
print 'Socket Bind Success!'
# listen(): This method sets up and start TCP listener.
s.listen(10)
print 'Socket is now listening'
while 1:
conn, addr = s.accept()
print 'Connect with ' + addr[0] + ':' + str(addr[1])
#receiver
buf = conn.recv(64)
#sender
send=conn.send(list)
print buf
print 'Connect close with ' + addr[0] + ':' + str(addr[1])
s.close()
And I wanna read list from python serwer then i create BufferedReader(new InputStreamReader) to receive data from python but is not going working well.
package com.javacodegeeks.android.androidsocketclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 8888;
private static final String SERVER_IP = "192.168.0.108";
private BufferedReader input;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) throws IOException {
try {
this.input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
} catch (IOException e)
{
e.printStackTrace();
}
String read = input.readLine();
Log.d("INFO", "onClick: "+read.toString());
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Do you have any ideas why i cant read this list?
Related
I have an app which has to poll a TCP server (on LAN) to fetch some data, I'm doing this using sockets in an AsyncTask class.
It works well for the first few requests. But at a certain point, the app must poll the server every 2s (using a timer). This is when the AsyncTask stops executing and the TCP messages do not get sent to the server. I can't figure out why.
Code is below. Any help will be appreciated!
Thank you!
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class TcpTask extends AsyncTask<String, Void, String> {
Context context;
TcpResultListener tcpResultListener;
int actionCode;
String TAG = "TcpTask";
String SERVER_IP = "192.168.1.12", SERVER_PORT = "1234";
Socket socket = null;
PrintWriter out;
int readTimeout;
// Creating listener
public void setOnTcpResultsListener(TcpResultListener tcpResultListener, int actionCode) {
this.tcpResultListener = tcpResultListener;
this.actionCode = actionCode;
}
// Constructor with context as parameter
public TcpTask(Context context, int timeout) {
this.context = context;
this.readTimeout = timeout;
}
#Override
protected String doInBackground(String... params) {
String result = null;
try {
//Create a client socket and define internet address and the port of the server
socket = new Socket(params[0], Integer.parseInt(params[1]));
Log.d(Constants.TAG, "Socket created");
//Setting timeout for readLine
socket.setSoTimeout(readTimeout);
Log.d(Constants.TAG, "Timeout set");
//Get the output stream of the client socket
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(Constants.TAG, "PrinterWriter created");
//Write data to the output stream of the client socket
out.println(params[2]);
Log.d(Constants.TAG, "Sending TCP data: " + params[2]);
//Get the input stream of the client socket
InputStream is = socket.getInputStream();
//Buffer the data coming from the input stream
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//Read data in the input buffer
result = br.readLine();
} catch (NumberFormatException e) {
Log.d("TcpException", e.toString());
} catch (UnknownHostException e) {
Log.d("TcpException", e.toString());
} catch (IOException e) {
Log.d("TcpException", e.toString());
}
try {
Log.d(Constants.TAG, "Socket:: " + socket);
if(socket != null){
socket.close();
}
} catch (IOException e) {
Log.d(Constants.TAG, e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
Log.d(Constants.TAG, "String:: " + result);
tcpResultListener.onResultsReceived(result, actionCode);
}
}
The method I use to call the AsyncTask:
void sendTCP(String msg) {
TcpTask tcpTask = new TcpTask(this, 8000);
// Setting listener for tcpTask to send back result
tcpTask.setOnTcpResultsListener(AddSpaceActivity.this, 1);
// TODO: Change the data being passed below
//Pass the server ip, port and client message to the AsyncTask
tcpTask.execute(gwIP, gwPort, msg);
}
EDIT: Timer code:
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d(Constants.TAG, "Timer fired:: " + firstReceived);
if(firstReceived){
sendTCP(Constants.NETWORK_STATUS_REQUEST);
}
}
}, 3000, 2000);
My problem when I try to send a simple "hello world" msg from the pc "client " to the phone "server " and
I tried all possible solution like : starting the server app which is on the phone first then the client but didn't work,
I changed the ip address too but didn't work,
I closed the firewall nothing happened too
Server's code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public class Server{
public void main(String args[]) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(5000);} catch (IOException e) {
e.printStackTrace();
}
while (true) {
// Wait for a client connection.
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
// Create and start a thread to handle the new client
try {
// Get the socket's InputStream, to read bytes
// from the socket
InputStream in = clientSocket.getInputStream();
// wrap the InputStream in a reader so you can
// read a String instead of bytes
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, Charset.forName("UTF-8")));
// Read from the socket and print line by line
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(getApplicationContext(),line,Toast.LENGTH_LONG).show();
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
// This finally block ensures the socket is closed.
// A try-with-resources block cannot be used because
// the socket is passed into a thread, so it isn't
// created and closed in the same block
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}}
Client's code:
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class ClientClass {
public static void main(String args[]) {
try (Socket socket = new Socket("192.168.1.3", 5000);) {
// We'll reach this code once we've connected to the server
// Write a string into the socket, and flush the buffer
OutputStream outStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
writer.println("Hello world!");
writer.flush();
} catch (IOException e) {
// Exception should be handled.
e.printStackTrace();
}
}
}
error:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at ClientClass.main(ClientClass.java:10)
BUILD SUCCESSFUL (total time: 2 seconds)
I was having same error, and i managed to know what causes this error in my case, you have to check two things:
1-Router configuration if you are connected using WiFi because you have to forward your port correctly.(How to Set Up Port Forwarding on a Router, it differs according to router type)
2-If this IP address here is the correct IP address of your mobile or not:
Socket socket = new Socket("192.168.1.3", 5000);
(How To Check Your Android IP Address)
In the MainActivity class, the inner class named Server is never instantiated and the "main" method is neither called too.
Please have a look to this Tutorial post so as to have an example of how to implement a server using sockets with android devices.
i'm new to wifi direct and i want to be able to broadcast a message, because i have a timeline and when i click the Post button i want all the connected devices have that message displayed on their timeline. I am able to send data peer to peer.I have searched about this subject and i found using UDP is a good choice but i don't know how to implement it in wifi direct.
I found this code that uses UDP on wifi to Get the Broadcast Address
InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);}
and this for Sending and Receiving UDP Broadcast Packets
DatagramSocket socket = new DatagramSocket(PORT);
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
could you please help me and explain to me how it works
thanks in advance.
In Android's Wi-Fi P2P there is a concept of "group owner", which is the device that acts as an access point. For the current API the group owner's IP address seems to be set to 192.168.49.1, which I think is hard-coded somewhere. A quick guess on the broadcast address for the group's network will be 192.168.49.255. For all (of a few) devices I have tested so far that turned out to be the case.
One solution is to Multicast a packet to a Multicast Group. All the devices join a Multicast IP and the sender sends the packet to that Multicast IP. Make sure IP you assign falls in the range of Multicast IPs. When dealing with Multicasting, the device needs to acquire a Multicast Lock. Note that since Multicast is based on UDP, some errors in transmissions are expected.
AsyncTask Class for Devices that will receive the packet:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class ReceiverMulticastAsyncTask extends AsyncTask<Void, Integer ,String > {
#Override
protected String doInBackground(Void... params) {
//Acquire the MulticastLock
WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifi.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
//Join a Multicast Group
InetAddress address=null;
MulticastSocket clientSocket=null;
try {
clientSocket = new MulticastSocket(1212);
address = InetAddress.getByName("224.0.0.1");
clientSocket.joinGroup(address);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DatagramPacket packet=null;
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, buf.length);
//Receive packet and get the Data
try {
clientSocket.receive(packet);
byte[] data = packet.getData();
Log.d("DATA", data.toString()+"");
} catch (Exception e) {
e.printStackTrace();
}
multicastLock.release();
try {
clientSocket.leaveGroup(address);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clientSocket.close();
return "";
}
#Override
protected void onPostExecute(String result) {
//do whatever...
}
}
AsyncTask Class for Device that will send the packet:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class SenderMulticastAsyncTask extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void... params) {
int port =1212;
DatagramSocket socket=null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress group = null;
try {
group = InetAddress.getByName("224.0.0.1");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
socket.close();
e.printStackTrace();
}
//Sending to Multicast Group
String message_to_send ="Test";
byte[] buf = message_to_send.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
try {
socket.send(packet);
Log.d("Send", "Sending Packet");
} catch (IOException e) {
// TODO Auto-generated catch block
socket.close();
e.printStackTrace();
}
socket.close();
return "";
}
#Override
protected void onPostExecute(String result) {
//do whatever ...
}
}
I have a broadcast receiver set up to listen for any SMS Received. I want to send this data over a socket back to a python server I have running on my local machine. I've set up a Toast notification to prove to my self that the broadcast receiver works whenever it receives a SMS. Before i added the sending data over a socket the toast would appear inside or outside the application, but after adding the socket portion the toast not only does the data not get sent over the socket but the toast doesn't show up either.
Here is my SMSReciever.java
import java.net.Socket;
import java.net.UnknownHostException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
public class SMSReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
//---"From: " +smsMessage[0].getDisplayOriginatingAddress() + " Text: " + smsMessage[0].getDisplayMessageBody();
// show first message
Toast toast = Toast.makeText(context, "From: " +smsMessage[0].getDisplayOriginatingAddress() + " Text: " + smsMessage[0].getDisplayMessageBody(), Toast.LENGTH_LONG);
toast.show();
Socket socket;
try {
socket = new Socket("10.0.2.2", 7000);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("Hello from Android");
out.flush();
out.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
try{
Socket socket = new Socket("10.0.2.2",7000);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("From: " +smsMessage[0].getDisplayOriginatingAddress() + " Text: " + smsMessage[0].getDisplayMessageBody());
socket.close();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
*/
}
}
and here is the python server which listens for connection and prints out the data recieved onto the terminal
server.py
from socket import *
HOST = "127.0.0.1" #local host
PORT = 7000 #open port 7000 for connection
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2) #how many connections can it receive at one time
print "Server started at 127.0.0.1:7000"
conn, addr = s.accept() #accept the connection
print "Connected by: " , addr #print the address of the person connected
while True:
data = conn.recv(5084) #how many bytes of data will the server receive
print "Received: ", repr(data)
conn.close()
I have written a small client server application for android. The client is a Java program running on my PC while my Android phone is a server. I'm facing force close issues in my server program. The server starts pretty good, but when I send a string from my PC client, the android application (server) force closes. It has become really annoying. Please help!
Here is my client program running on my PC:
package javaNetPackage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
public class javaClient {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String serverIpAddress = "10.81.242.220";
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
echoSocket = new Socket(serverAddr, 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to server");
System.exit(1);
}
String str = JOptionPane.showInputDialog("Please give number");
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(echoSocket.getOutputStream())),true);
out.println(str);
out.close();
in.close();
echoSocket.close();
}
}
And here is my server code running on Android:
package com.vinit.androidserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MainActivity extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 4444;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("Nothing from client yet");
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(mClientMsg);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Permissions:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Update:: Okay, I solved the issue of force close. I deleted the permission tags in manifest.xml and re-typed them. But now, I'm facing a different problem here. The sent string from PC client is not getting displayed in my server TextView (textView1 in layout xml, referred to as tv in server code). Default message in tv is "Nothing from client yet". When I send a string from PC client, default message disappears but sent string is not updated in server TextView (tv).
You should set the received string to your Message object sent in myUpdateHandler.sendMessage(m); instead of your mClientMsg field.
You can create and send the Message object as below:
String st = null;
st = input.readLine();
Message msg = Message.obtain(myUpdateHandler, MSG_ID, st);
msg.sendToTarget();
To get the value in your handler,
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText((String) msg.obj);
break;
I would suggest you use a Bundle object instead of the raw object though. http://developer.android.com/reference/android/os/Message.html#setData(android.os.Bundle)
The reason you ends up with an empty string is because your handler and CommsThread run in different threads and thus not using the same instance of mClientMsg.
i.e. changes in CommsThread to mClientMsg is not visible in your handler.