Faced a weird problem when TCP connection via Socket is not established on Android 4.4 for some reason. It works fine on 4.1.1 and 5.0.
#Override
protected Void doInBackground(Void... params) {
try {
// Creating InetAddress object from ipNumber passed via constructor from IpGetter class.
InetAddress serverAddress = InetAddress.getByName(host);
// Create a new Socket instance and connect to host
socket = new Socket(serverAddress, port);
Log.i(TAG, "Socket created: " + host + ":" + port);
// Create PrintWriter object for sending messages to server.
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); //thread freezes here
//Create BufferedReader object for receiving messages from server.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d(TAG, "In/Out created");
} catch (UnknownHostException e) {
Log.e(TAG, "Don't know about host: " + host + ":" + port);
connected = false;
Log.e(TAG, e.getMessage());
} catch (IOException e) {
Log.e(TAG, "Couldn't get I/O for the connection to: " + host + ":" + port);
connected = false;
Log.e(TAG, e.getMessage());
}
connected = true;
return null;
}
For some reason Thread stops on I/O creation.
Any ideas what causes this? Maybe someone seen that problem before?
Related
Evening fellow programmers,
am relatively new to android studio, and it's my first time dealing with bluetooth, receivers, broadcasts and such stuff.. I followed some tutorials and created my monitoring app, the app is supposed to read data sent by HC-06 module from arduino, yet I had a pump with the connect thread, it keeps catching the socket.close() instead of trying the socket.connect() and I have no idea why is that happening..
here is the code for my ConnectThread.run():
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket
using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket
" + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection
in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " +
MY_UUID_INSECURE );
}
connected(mmSocket,mmDevice);
}
And the thrown exception:
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket#3390c6f, mSocketState: INIT
D/BluetoothConnectionServ: run: Closed Socket.
run: ConnectThread: Could not connect to UUID: 00001101-0000-1000-8000-00805f9b34fb
connected: Starting.
However, connectedThread continues to work even when the socket is closed, idk if that's how it works, but here is the ConnectedThread.run():
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
Intent incomingMessageIntent = new Intent("incomingMessage");
incomingMessageIntent.putExtra("theMessage",incomingMessage);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(incomingMessageIntent);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
And its exceptions:
D/BluetoothConnectionServ: ConnectedThread: Starting.
E/BluetoothConnectionServ: write: Error reading Input Stream. socket closed
I am having trouble connecting two android phones via socket i am using android debug bridge to connect the phones to my PC from which i can launch the emulator on the phones.
I launch the server on one phone and try to connect with the other however i get the following error on my client side:
W/System.err: java.net.ConnectException: failed to connect to /192.168.49.1 (port 8080): connect failed: ECONNREFUSED
Server
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
Log.d("Quiz", "Server creation connection success");
Log.d("Quiz", "Server local port "+serverSocket.getLocalPort());
Log.d("Quiz", "Server local port "+serverSocket.getInetAddress());
HostingScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
HostingScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client
#Override
protected Object doInBackground(Object[] params) {
Socket socket = null;
try {
socket = new Socket(host,port);
Log.d("Quiz", "Client socket success");
connected = true;
while (connected) {
try {
Log.d("Quiz", "Sending command");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
} catch (Exception e) {
}
}
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
The port is hard coded to port 8080 for both the server and the client for the time being, the host address is found when i make a connection between the phones by using the following code:
Connection
private void onConnectionChanged(Intent intent) {
final NetworkInfo netInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
final WifiP2pInfo p2pInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO);
isConnected = netInfo.isConnected();
if (isConnected) {
//Get host connection info
wifiMgr.requestConnectionInfo(channel, new ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
wifiMgr.requestGroupInfo(channel, new GroupInfoListener() {
#Override
public void onGroupInfoAvailable(WifiP2pGroup group) {
if (group == null)
return;
WiFiP2P.this.group = group;
Log.d(TAG, "Wifi p2p connection group is " + group.getNetworkName());
Log.d(TAG, "Group size " + group.getClientList().size());
fireOnConnectionSucceed(group.getNetworkName(), group.getPassphrase());
//create client if not host
if(info.isGroupOwner) {
Client client = new Client(8080, p2pInfo.groupOwnerAddress.getHostAddress());
client.execute();
Log.d(TAG, "Client launch success");
Log.d(TAG, "Host address " + p2pInfo.groupOwnerAddress.getHostAddress());
}
}
});
if (isConnected && !info.isGroupOwner) {
} else {
startDiscovery();
}
}
});
} else {
group = null;
fireOnConnectionLost();
}
}
I check to see if the person connected is the host or not, if not i launch the client passing the port and host address to the client which is an Aysnc task where the socket to connect is created.
The error occurs in the client when
socket = new Socket(host,port);
is used causing the error stated.
Any ideas as to what the problem could be? They both connect to each other over WiFi but when i try to connect to the server socket it fails.
Thanks in advance.
Edit:
To clear somethings up, i use the adb to get the app from my computer onto my phone from which i can launch the app.
I am connecting both phones using wifimanager i need to find which of the phones created the wifi group and then that person is the host of the server to which i can connect the problem arises when i try to launch a socket to connect to the host using the host address from the connect info.
I managed to solve my problem, it turns out the device which was hosting the server wasn't being designated the group owner.
config.groupOwnerIntent=0;
Setting the owner intent of connecting devices to 0 fixed the problem.
I want to make my android app open socket to my windows console app and they communicate with each other. The socket is opened and data is sent and received in windows app, but my android app does not receive the answer which sent by windows. I watch the packets in my android and I saw the packets are coming but I do not know why my app do not receive it!
windows app server class:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
Console.WriteLine("\nStarting server...");
this.tcpListener = new TcpListener(IPAddress.Any, 1234);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
Console.WriteLine("\nWaiting for clients to connect...");
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
Console.WriteLine("\nIncoming from client...");
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
try
{
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("\nReceived: \n\n" + encoder.GetString(message, 0, bytesRead));
//By FMR
string response = "random responsive: " + new Random().Next(1000).ToString() + "\n";//"\r\n";
//writeData(clientStream, response);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
clientStream.Write(msg, 0, msg.Length);
clientStream.Flush();
Console.WriteLine("\nResponed ..." + response);
}
}
catch (Exception ex)
{
Console.WriteLine("\nException while: " + ex.Message);
}
tcpClient.Close();
}
}
my android thread:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Socket socket = null;
ServerSocket serverSocket = null;
Boolean bRun = true;
try {
socket = new Socket(ip, port);
if(outputStream == null) {
outputStream = new DataOutputStream(socket.getOutputStream());
}
// become server
serverSocket = new ServerSocket(port);
Log.i(G.TAG, "before serverSocket.accept");
socket = serverSocket.accept();
Log.i(G.TAG, "response recieve: ");
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e) {
try {
serverSocket.close();
} catch (IOException e1) {
Log.e(G.TAG, "serverSocket.close() e: " + e1.getMessage());
}
try {
socket.close();
} catch (IOException e1) {
Log.e(G.TAG, "socket.close() e: " + e1.getMessage());
}
}
Log.i(G.TAG, "after start recieve: ");
while (bRun) {
try {
Log.i(G.TAG, "while start: ");
String message = inputStream.readLine();
Log.i(G.TAG, "response message: " + message);
if (message != null) {
setListMessage(false, message);
}
}
catch (IOException e) {
bRun = false;
Log.e(G.TAG, "while bRun e: " + e.getMessage());
}
}
}
});
thread.start();
// in another function, my message is sent successfully from android and receive in windows
I found the problem, this line
socket = serverSocket.accept();
made the problem when I comment the line, the android app received the response!
Does anybody know why?
i want to send data(latitude and longitude )to a web server (windows server 2008) who"s ip and udp port is known from my android application .how to do so ?
here is a sample code which i m trying but data is not received to other end
public class UDPServer extends Activity {
WebView view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState) ;
setContentView(R.layout.main);
view=(WebView) findViewById(R.id.webView1);
try {
String serverHostname = new String ("ip and udp port");
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName(serverHostname);
System.out.println ("Attemping to connect to " + IPAddress +
") via UDP port 7777");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
System.out.print("Enter Message: ");
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Log.i("send","send");
System.out.println ("Sending data to " + sendData.length +
" bytes to server.");
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,7777);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
System.out.println ("Waiting for return packet");
clientSocket.setSoTimeout(10000);
try {
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
InetAddress returnIPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println ("From server at: " + returnIPAddress +
":" + port);
System.out.println("Message: " + modifiedSentence);
}
catch (SocketTimeoutException ste)
{
System.out.println ("Timeout Occurred: Packet assumed lost");
}
clientSocket.close();
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
}
In UDP, unlike TCP, there is no connection established. Every UDP packet travels on it's own.
My guess is that you can send a UDP packet to server, but you do not receive the return packet. The reason for this is NAT which is used on all home routers and cellular networks. NAT prevents delivery of inbound (internet to device) packets.
To test this assumption, try this with device and server on the same local network.
I'm using an Android client to connect to a Python server. here is my Android client code, which connects via mobile Samsung mini galaxy to the sever via Open socket using same wireless IP address:
public void appendText(View view){
Text.append( "\n In chat ");
try{
// while (true)
//{
sentence=inputfld.getText().toString();
String sentence1=("hohohoh");
Text.append( "\n DataStream creating");
outToServer.writeBytes(sentence);
outToServer.writeBytes(sentence1);
modifiedSentence = inFromServer.readLine();
Text.append(modifiedSentence);
inputfld.setText(null);
}
}
catch(Exception modifiedsentence){
Text.append("Exception");
}
}
public void connect(View view){
try {
String cmd=("My current location is: " );
clientSocket= new Socket("192.168.1.2",54628);
Text.append( "\n created a socket");
outToServer = new DataOutputStream(clientSocket.getOutputStream());
Text.append( "\n created a datastream");
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Text.append( "\n created a bufferReader");
Text.append( "\n created a socket");
} catch (SocketException e) {
e.printStackTrace();
}
catch(Exception e){
System.out.println("Error");
}
}
The problem now is that I can connect and I have button to send on action event for appendtext, but it didn't let me send using the mobile. What is wrong in my code?