Hi I'm trying to send data from android client to a Python server on my PC, here is the code I don't really know what I'm doing wrong, (I'm not sure I understood how tcp sockets work on Javascript), I'm new to coding, I run this program when my mobile is connected to PC with USB.
Javascript Client:
package com.example.app;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.idBtn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"should do something",Toast.LENGTH_SHORT).show();
BackgroundTask b = new BackgroundTask();
b.execute();
}
});
}
class BackgroundTask extends AsyncTask<String,Void,String>
{
Socket s;
DataOutputStream dos;
String message;
#Override
protected String doInBackground(String... strings) {
message = "Hello_Javascript";
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.7");
s = new Socket(serverAddr, 10000);
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(message);
dos.close();
}catch(IOException e){
e.printStackTrace();
}
return null;
}
}
}
Python Server (should be ok since I can communicate with another Python Client)
import socket
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print('starting up port ', server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from ', client_address)
# Receive the data in small chunks and retransmit it
data = connection.recv(100)
print('received ', data)
finally:
# Clean up the connection
connection.close()
Thank you in advance!
You can use emulator to check if it works.Because both share same server this way
Related
I'm making an android app via android studio that displays accelerometer data on the screen and I tried to send this to my laptop via sockets, but the app closes by itself after sending this data once to my laptop.
here's a code sample of the socket class
public class MessageSender extends AsyncTask<String, Void, Void> {
Socket sock;
DataOutputStream dos;
PrintWriter pw;
#Override
protected Void doInBackground(String... voids) {
String message = voids[0];
try
{
sock = new Socket("192.168.0.105", 8400);
pw = new PrintWriter(sock.getOutputStream());
pw.write(message);
pw.flush();
}catch (IOException ioe){
ioe.printStackTrace();
}
return null;
}}
Here's the mainActivity code:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private SensorManager sensorManager;
Sensor accelerometer;
MessageSender messenger = new MessageSender();
TextView xValue, yValue, zValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xValue = (TextView) findViewById(R.id.xValue);
yValue = (TextView) findViewById(R.id.yValue);
zValue = (TextView) findViewById(R.id.zValue);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#SuppressLint("SetTextI18n")
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
Log.d(TAG, "onSensorChanged: X" + sensorEvent.values[0] + " Y: " +
sensorEvent.values[1] + " Z: " + sensorEvent.values[2]);
xValue.setText("X-axis: " + sensorEvent.values[0]);
yValue.setText("Y-axis: " + sensorEvent.values[1]);
zValue.setText("Z-axis: " + sensorEvent.values[2]);
messenger.execute("{\"X\":"+sensorEvent.values[0]+", \"Y\":"+sensorEvent.values[1]+", \"Z\":"+sensorEvent.values[2]+"}");
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}}
My laptop acts as the server with a python script, the code for which is below:
import socket
import json
TCP_IP = '192.168.0.105'
TCP_PORT = 8400
BUFFER_SIZE = 1024 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print('Connection address:', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
parseData = json.loads(data)
if not data: break
print("received data:")
print(parseData)
conn.send(data) # echo
conn.close()
this is the error I'm getting on my python console:
received data:
{'X': -0.25576973, 'Y': -0.12328009, 'Z': 9.587313}
Traceback (most recent call last):
File "C:/Users/theva/Desktop/server.py", line 15, in <module>
data = conn.recv(BUFFER_SIZE)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
I'm trying to get the app to continuously send data to my pc as long as the connection is maintained else just display that data on the mobile screen
I'm probably doing this the wrong way but please help me with this, I don't mind criticism but just say it in simple layman terms please.
Thanks in advance!
messenger.execute("{"X":"+sensorEvent.values[0]+....
You can only call execute() once for an AsyncTask instance.
Dont use a global AsyncTask instance but create a new one for every message.
And if you want a permanent connection then use two async tasks. One to establish the connection. The other to send data.
The server is Python and the client is Kotlin. When I send String from the server, String is printed from the client.
The simple code is here, but the client doesn't print it.
What could be the problem?
Server code
# server.py
import socket
from PyQt5.QtCore import QThread
host = '192.168.0.22'
port = 5000
server_sock = socket.socket(socket.AF_INET)
server_sock.bind((host, port))
server_sock.listen(1)
client_sock, addr = server_sock.accept()
print('Connected by', addr)
data="1234567"
client_sock.send(data.encode())
client_sock.close()
server_sock.close()
Client code
package com.cfsuman.client
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.io.DataInputStream
import java.net.Socket
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val thread = Thread(Runnable {
var socket = Socket("192.168.0.22", 5000)
var input = socket.getInputStream()
var dis = DataInputStream(input)
var data_input = dis.read()
println(data_input)
socket.close()
}).start()
}
}
So I am trying to send data from the raspberry pi to unity.
I trying to create socket server to do so.
I can get the socket server running on the raspberry pi and can also look at the port with netstat -tulpn | grep :5005 in the terminal on the machine where the python script is running.
I also tried it on my mac and it also showed up as a TCP-server.
However when I try to connect to the same port and ip via Unity or on another machine it doesn't work. I also can't seem to find the port when listing all of the ports with netstat.
Unity spits out a "Connection refused" error.
Here is the code in Unity in C#
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net.Sockets;
public class ClientSocket : MonoBehaviour
{
bool socketReady = false;
TcpClient mySocket;
public NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
public String Host = "192.168.8.137";
public Int32 Port = 5005;
void Start()
{
setupSocket();
TextMessage("SocketTest");
}
public void setupSocket()
{ // Socket setup here
try
{
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e)
{
Debug.Log("Socket error:" + e); // catch any exceptions
}
}
public void TextMessage(string message)
{
if (socketReady == true)
{
theWriter.Write(message);
theWriter.Flush();
}
}
}
here is the code in python, which should be running on the raspberry pi.
import socket
import sys
backlog = 1
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.8.137', 5005))
s.listen(1)
try:
print ("is waiting")
client, address = s.accept()
while 1:
data = client.recv(size)
if data:
print (data)
finally:
print("closing socket")
cient.close()
s.close()
I'm new to socket servers, but I really trying to accomplish a connection here.
Thanks for reading!
am pretty sure you need to encode the data that you about to send in c# TcpClient
adding an example from my final project:
string data = "Hello Server!"; //the message in string (important it will be string)
byte[] msg = Encoding.Unicode.GetBytes(data); //encoded the message using unicode (utf-16)
NetworkStream stream = client.GetStream(); //get the tcp client stream
stream.Write(msg, 0, msg.Length); //write the message to the stream
and in the server you suppose to have something like that:
msg = clnt.recv(1024) #reciving the data
msg = msg.decode("utf-16") #decoding the data
print(msg) #printing the data
and i think thats it
and i would recommend using port above 10000 because most of the ports can be used
I am trying to connect my android app (client) to my PC (python server). They are both on the same network. I can ping my android phone from my PC and PC from phone. But when I try to connect them using sockets android app gets stuck at connecting and after a while throws a timeout exception.
Here is the code of Android Client class:
public class Client extends AsyncTask<Void, Void, Void> {
private String mCommand;
private String mHostIP;
public Client(String mCommand, String mHostIP) {
this.mCommand = mCommand;
this.mHostIP = mHostIP;
}
#Override
protected Void doInBackground(Void... voids) {
try {
InetAddress serverAddr = InetAddress.getByName(mHostIP);
Socket soc = new Socket(serverAddr,9999);
OutputStream toServer = soc.getOutputStream();
PrintWriter output = new PrintWriter(toServer);
output.println(mCommand);
DataOutputStream out = new DataOutputStream(toServer);
out.writeBytes(mCommand);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
It gets stuck at new Socket and throws exception after a while.
Here is the code for Python server:
import socket
import os
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print('My IP: '+IPAddr)
port = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("socket successfully created")
server_address = ('192.168.10.4', 9999)
s.bind(server_address)
s.listen(1)
print ("socket is listening")
while True:
try:
c, addr = s.accept()
print ('Got connection from', addr)
type = c.recv(1024).decode('utf-8')
print(type)
finally:
print('Could not connect')
c.close()
break
Have a close look at your firewall.
I am trying to establish a connection between an android phone(as server) and my computer(client in python) to send messages from the android phone to PC.
My Problem is that the app keeps crashing and I don't really know how to set the ip's.
So what I do is when the app opens I give it the computers IP and the port at which I need to send the message and then I click "send button".
Down below I have given the code that I have tried but the app crashes at the socket.send(sendPacket);
Android Code
public class MainActivity extends Activity {
private EditText ipInput;
private EditText portInput;
private EditText messageInput;
private Button sendButton;
private DatagramSocket socket;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipInput = (EditText) findViewById(R.id.address);
portInput = (EditText) findViewById(R.id.port);
messageInput = (EditText) findViewById(R.id.message);
sendButton = (Button) findViewById(R.id.send);
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String message = messageInput.getText().toString();
Log.e("TAG",message);
sendPacket(message);
}
});
}
private void sendPacket(String message) {
byte[] messageData = message.getBytes();
try {
InetAddress addr = InetAddress.getByName(ipInput.getText().toString());
int port = Integer.parseInt(portInput.getText().toString());
DatagramPacket sendPacket = new DatagramPacket(messageData, 0, messageData.length, addr, port);
if (socket != null) {
socket.disconnect();
socket.close();
return;
}
socket = new DatagramSocket(port);
socket.send(sendPacket);
} catch (UnknownHostException e) {
Log.e("MainActivity sendPacket", "getByName failed");
} catch (IOException e) {
Log.e("MainActivity sendPacket", "send failed");
}
}
#Override
public void onDestroy() {
super.onDestroy();
socket.disconnect();
socket.close();
}
}
Python Code:
My python code is also there, I bind the IP at 0.0.0.0 so I can get packet from anyone trying to communicate.
from socket import *
PORT = 7000
IP = "0.0.0.0"
sock = socket(AF_INET, SOCK_DGRAM) # SOCK_DGRAM means UDP socket
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind((IP, PORT))
while True:
print "Waiting for data..."
data, addr = sock.recvfrom(1024) # blocking
print "received: " + data
To sum it all up. I really need help with setting ip's, whose ip should I give to the android phone(the phone's or the laptops) and whose ip should I give to the laptop in the python code.
Secondly why does the app crash at "socket.send(sendPacket);" inside the send packet method.
If you need more details let me know in the comments.
So I can't answer you why the app is crashing but I can answer the IP question.
The client (laptop) needs the servers ip (in the same network its 192.168.X.XXX).
The server (phone) might also need his own ip.
The client might also need his own ip.
But notice that the server doesn't need the clients ip, it's open for all connections (except you want to white/black-list certain ip´s).
I did the same things with just some ip differences, works for me.
I have an app on which i press a button and it should turn on/off an led on a raspberry pi.
the code on android studio looks like this :
onPressed: () async {
setState(() {
instruction = power;
power = power == 'on' ? 'off' : 'on';
print('$instruction');
});
int port = 9999;
final socket = await EasyUDPSocket.bindBroadcast(port);
if (socket != null) {
socket.send(ascii.encode('$instruction'), '192.168.0.105', port);
final resp = await socket.receive();
print('Client $port received: $resp');
// `close` method of EasyUDPSocket is awaitable.
await socket.close();
print('Client $port closed');
}
},
the '192.168.0.105' is the ipv4 address of the raspberry pi(this can be found by typing "ipconfig" for windows in cmd and by "ifconfig" in an rpi)
the python code on the rpi or any pc will be
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
print("socket created")
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(("192.168.0.105",9999))
while True:
print("Waiting for data...")
data, addr = s.recvfrom(1024) # blocking
instruction = data.decode("utf-8")
if instruction == 'off':
print('turn off the led')
else:
print("turn on the led")
the python code is a bit customized for the led purpose but i'm sure you'll understand how to work with it!