I have a PlayerActivity class, and a PlayerConnect class.
Previously, I used PlayerActivity class to start a thread that would run PlayerConnect. I recently found that the thread misbehaves a little, and have been recommended to use services (for this: IntentServices).
Problem: My logs tell me that the IP, name, and init are null, null, 0, which should not be the case as they are supposed to be set before the point of starting the service. Logs also tell me that it's failing to connect to the localhost, which I think it's defaulting to because it doesn't have a set IP to try.
Am I correctly referencing the PlayerConnect class in my Intent?
PlayerActivity:
public class PlayerActivity extends AppCompatActivity {
InetAddress hostIP;
String playerName;
int playerInitiative = -1;
boolean denied = false;
boolean started = false;
PlayerConnect playerConnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!(playerName.equals("")) && playerInitiative > -1) {
try {
if (!(hostIPString.equals(""))) {
hostIP = InetAddress.getByName(hostIPString);
if(!(started)) {
playerConnect = new PlayerConnect();
playerConnect.SetHostIP(hostIP);
playerConnect.SetPlayerName(playerName);
playerConnect.SetPlayerInit(playerInitiative);
denied = playerConnect.GetDenied();
started = true;
}
else {
playerConnect.SetHostIP(hostIP);
playerConnect.SetPlayerName(playerName);
playerConnect.SetPlayerInit(playerInitiative);
denied = playerConnect.GetDenied();
}
if (denied)
{
started = false;
}
else
{
Intent playerConnectIntent =
new Intent(PlayerActivity.this, playerConnect.getClass());
startService(playerConnectIntent);
}
}
}
catch (Exception e) {
Log.i("LOG", e.toString());
}
}
}
});
}
}
PlayerConnect:
public class PlayerConnect extends IntentService {
public PlayerConnect() {
super("PlayerConnect");
}
InetAddress hostIP;
String playerName;
int playerInitiative;
boolean denied = false;
#Override
public void onHandleIntent(Intent intent) {
SendPlayerData(hostIP, playerName, playerInitiative);
}
private void SendPlayerData(InetAddress IP, String name, int init) {
try {
int port = 8080;
Socket socket = new Socket();
socket.connect(new InetSocketAddress(IP, port), 3000);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
if (socket.isConnected())
{
output.writeUTF(name);
output.writeInt(init);
output.close();
socket.close();
Log.i("LOG", "client socket connected");
}
if (socket.isClosed())
{
stopSelf();
Log.i("LOG", "client socket closed");
}
}
catch (Exception e) {
denied = true;
Log.i("LOG", e.toString());
Log.i("LOG", IP + name + init);
}
}
public void SetHostIP(InetAddress host)
{
hostIP = host;
}
public void SetPlayerName(String name)
{
playerName = name;
}
public void SetPlayerInit(int init)
{
playerInitiative = init;
}
public boolean GetDenied()
{
return denied;
}
}
greeble31 Your comment helped me a lot, so I'm making it the answer for future readers. Thank you.
No, you never want to construct a Service subclass yourself (new PlayerConnect()). That's the system's job. The one it gives you in response to a startService() call will be completely different from the one you get back from the constructor, so it won't have any of the data you added to it. You need to add your data to playerConnectIntent, and retrieve it in onHandleIntent().
Related
I have a server set up on my PC (using Hercules), which is listening on a port # and waiting for a connection. I can't get the android app to receive messages from the server however on my android emulator (Strangely I can send messages to the server), and I can't do either from my physical android phone.
All the examples I'm finding online involve android devices connecting to each other, like this one: https://www.coderzheaven.com/2017/05/01/client-server-programming-in-android-send-message-to-the-client-and-back/
Would I still be able to connect to a PC by just implementing the client side on my android app? What changes would I have to make otherwise?
Directly copy pasting hasn't worked for me...
(Btw the phone and PC are both connected to the same ethernet network, not wifi if that makes a difference)
Thanks!
edit: Turns out my PC was on a different subnet from my phyiscal android phone, and so changing the PC to be on the same subnet as the phone fixed the problem of my phone not being able to even connect, but now it can connect it seems and send messages to the PC, but again not able to receive messages from the hercules server
edit2: My client code (android app)
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int SERVERPORT = xxxx;
public static final String SERVER_IP = "xxx.xxx.x.xxx";
private ClientThread clientThread;
private Thread thread;
private LinearLayout msgList;
private Handler handler;
private int clientTextColor;
private EditText edMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Client");
clientTextColor = ContextCompat.getColor(this, R.color.colorAccent);
handler = new Handler();
msgList = findViewById(R.id.msgList);
edMessage = findViewById(R.id.edMessage);
}
public TextView textView(String message, int color) {
if (null == message || message.trim().isEmpty()) {
message = "<Empty Message>";
}
TextView tv = new TextView(this);
tv.setTextColor(color);
tv.setText(message + " [" + getTime() + "]");
tv.setTextSize(20);
tv.setPadding(0, 5, 0, 0);
return tv;
}
public void showMessage(final String message, final int color) {
handler.post(new Runnable() {
#Override
public void run() {
msgList.addView(textView(message, color));
}
});
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.connect_server) {
msgList.removeAllViews();
showMessage("Connecting to Server...", clientTextColor);
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
showMessage("Connected to Server...", clientTextColor);
return;
}
if (view.getId() == R.id.send_data) {
String clientMessage = edMessage.getText().toString().trim();
showMessage(clientMessage, Color.BLUE);
if (null != clientThread) {
clientThread.sendMessage(clientMessage);
}
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader input;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String message = input.readLine();
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
showMessage(message, Color.RED);
break;
}
showMessage("Server: " + message, clientTextColor);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
void sendMessage(final String message) {
new Thread(new Runnable() {
#Override
public void run() {
try {
if (null != socket) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
The idea here is to make a socket connection over the local network, send some data, and close the connection immediately. The only thing that should remain running is the serversocket. So far, everything works as expected except one thing:
When the activity that starts the serversocket gets closed with the back button, and then reopened, the data being sent from the client no longer makes it to the serversocket.
DMActivity:
public class DMActivity extends AppCompatActivity {
String ipAddress;
boolean dmListenRunning = false;
DMListen dmListen = new DMListen();
Thread dmListenThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dm);
if (!(dmListenRunning)) {
dmListenThread = new Thread(dmListen);
dmListenRunning = true;
dmListenThread.start();
}
}
#Override
public void onBackPressed()
{
try {
dmListen.KillThread(true);
dmListenThread.interrupt();
}
catch (Exception e)
{
Log.i("LOG", e.toString());
}
finish();
}
}
DMListen:
public class DMListen implements Runnable {
ServerSocket serverSocket;
boolean started = false;
boolean closeSockets = false;
boolean killed = false;
public void run() {
ReceivePlayerData();
}
public void ReceivePlayerData() {
try {
while (!(Thread.interrupted())) {
if (!(started)) {
int port = 8080;
serverSocket = new ServerSocket(port);
started = true;
}
Socket clientSocket = serverSocket.accept();
DataInputStream dataIn = new DataInputStream(clientSocket.getInputStream());
String name;
int init;
name = dataIn.readUTF();
init = dataIn.readInt();
dataIn.close();
clientSocket.close();
}
}
catch (Exception e) {
Log.i("LOG", e.toString();
}
if(killed)
{
try {
serverSocket.close();
if (Thread.currentThread().isInterrupted())
{
try {
Thread.currentThread().join();
}
catch (Exception e)
{
Log.i("LOG", e.toString());
}
}
}
catch(IOException e)
{
Log.i("LOG", e.toString());
}
}
}
public void KillThread(boolean k)
{
boolean killed = k;
}
}
PlayerActivity:
public class PlayerActivity extends AppCompatActivity {
EditText hostIPBox;
Button submit;
String hostIPString;
InetAddress hostIP;
boolean denied = false;
boolean started = false;
PlayerConnect playerConnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
hostIPBox = (EditText) findViewById(R.id.ipaddress);
hostIPBox.setRawInputType(Configuration.KEYBOARD_12KEY);
hostIPBox.setSingleLine();
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hostIPString = hostIPBox.getText().toString();
try {
if (!(hostIPString.equals(""))) {
hostIP = InetAddress.getByName(hostIPString);
if(!(started)) {
playerConnect = new PlayerConnect();
playerConnect.SetHostIP(hostIP);
denied = playerConnect.GetDenied();
started = true;
}
else {
playerConnect.SetHostIP(hostIP);
denied = playerConnect.GetDenied();
}
if (denied)
{
started = false;
}
else
{
new Thread(playerConnect).start();
}
}
}
catch (Exception e) {
Log.e("LOG", e.toString());
}
}
});
}
}
PlayerConnect:
public class PlayerConnect implements Runnable {
InetAddress hostIP;
boolean closeSockets = false;
boolean denied = false;
public void run() {
SendPlayerData(hostIP, playerName, playerInitiative);
}
private void SendPlayerData(InetAddress IP, String name, int init) {
try {
int port = 8080;
Socket socket = new Socket();
socket.connect(new InetSocketAddress(IP, port), 3000);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
if (socket.isConnected())
{
output.writeUTF(name);
output.writeInt(init);
output.close();
socket.close();
}
if (closeSockets) {
output.close();
socket.close();
closeSockets = false;
}
}
catch (Exception e) {
denied = true;
Log.i("LOG", e.printStackTrace());
}
}
public void SetHostIP(InetAddress host)
{
hostIP = host;
}
public boolean GetDenied()
{
return denied;
}
}
You should use Service to handle socket connection. You won't have problems with Activity lifecycle.
I'm learning how work handler in Android. I did Android server and socket class. I want send some message (i.e. "New Connect") from socket to mainactivity, when somebody connect to server. I can't figure out how to pass from socket to mainactivity. (More in comments)
HttpServerActivity.java
public class HttpServerActivity extends Activity implements OnClickListener{
private SocketServer s;
private static final int READ_EXTERNAL_STORAGE = 1;
Button btn1, btn2;
// There I'm trying to send message to button, when somebody connected
Handler h = new Handler(){
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
String text = (String)msg.obj;
btn1.setText(text);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_server);
Button btn1 = (Button)findViewById(R.id.button1);
Button btn2 = (Button)findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.http_server, menu);
return true;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
} else {
// I dont know figure out in this place
s = new SocketServer(h);
s.start();
}
}
if (v.getId() == R.id.button2) {
s.close();
try {
s.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case READ_EXTERNAL_STORAGE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// I dont know figure out in this place
s = new SocketServer(h);
s.start();
}
break;
default:
break;
}
}
}
SocketServer.java
public class SocketServer extends Thread {
private final Handler mHandler;
public SocketServer(Handler handler)
{
mHandler = handler;
}
ServerSocket serverSocket;
public final int port = 12345;
boolean bRunning;
public void close() {
try {
serverSocket.close();
} catch (IOException e) {
Log.d("SERVER", "Error, probably interrupted in accept(), see log");
e.printStackTrace();
}
bRunning = false;
}
public Handler mHandler;
public void run() {
try {
Log.d("SERVER", "Creating Socket");
serverSocket = new ServerSocket(port);
bRunning = true;
while (bRunning) {
Log.d("SERVER", "Socket Waiting for connection");
Socket s = serverSocket.accept();
Log.d("SERVER", "Socket Accepted");
// trying to send some message
String[] messageString = new String[1];
Message message = Message.obtain();
messageString[0]="OK";
message.obj = messageString;
mHandler.sendMessage(message);
OutputStream o = s.getOutputStream();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(o));
out.write("HTTP/1.0 200 OK\n" +
"Date: Fri, 31 Dec 1999 23:59:59 GMT\n" +
"Content-Type: text/html\n" +
"Content-Length: 1354\n" +
"\n" +
"<html>\n" +
"<body>\n" +
"<h1> Connected </h1>\n" +
"</body>\n" +
"</html>");
out.flush();
while (!((tmp = in.readLine()).isEmpty()))
{
Log.d("Header", tmp);
if (tmp.startsWith("GET"))
{
getRequest = tmp;
}
}
s.close();
Log.d("SERVER", "Socket Closed");
}
}
catch (IOException e) {
if (serverSocket != null && serverSocket.isClosed())
Log.d("SERVER", "Normal exit");
else {
Log.d("SERVER", "Error");
e.printStackTrace();
}
}
finally {
serverSocket = null;
bRunning = false;
}
}
}
This is a sample of a bigger project I was involved a few years ago. You will not be able to run as it is, but I think you can see how the communication between a Service and an Activity works. Feel free to ask if anything is not clear
Service
public class BluetoothService {
private final Handler mHandler;
public BluetoothService(Context context, Handler handler) {
mHandler = handler;
}
public synchronized void Connecting(...) {
...
Message MenssageToActivity = mHandler.obtainMessage(Cliente_Bluetooth.MESSAGE_HELLO);
Bundle bundle = new Bundle();
bundle.putString(BluetoothClient.DEVICE_NAME, " Gorkatan");
MensajeParaActivity.setData(bundle);
mHandler.sendMessage(MensajeParaActivity);
...
}
}
Activity
public class BluetoothClient{
public static final int MESSAGE_HELLO = 1;
public static final int MESSAGE_BYE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
mBluetoothService = new BluetoothService(this, mHandler);
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_HELLO:
String mName = null;
mName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Hello "+ mName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_BYE:
System.out.println("Bye!")
break;
}
Here it is the whole project (which has got comments and variable names in Spanish):
https://github.com/ignacio-alorre/PDF-Dispenser/tree/master/Client/Cliente_Bluetooth/src/com/cliente_bluetooth
If you plan on sending data from a thread to your handler then use obtainMessage to create a message object.
You must also use the same instance of the handler to handleMessage and sendMessage.
Here you will find a great resource explaining how to use Handler:
https://www.youtube.com/watch?v=LJ_pUlWzGsc
I am trying to write an Android app that could communicate over WiFi with ESP8266 module and exchange some simple, basic text data. My problem is I can not get any communication to work. I am not sure if my problem is with the Android code or some bad network configuration on the ESP.
On the Android side, I am using a standard TCPclient class code from this thread to transmit data. In this app I can get WiFi to work and to connect with ESP module using SSID and password authorization.
This is how my app looks like.
Here is TCPclient.java class code I used.
package com.example.wexfo.wifi_com;
import ...
public class TCPclient {
private String serverMessage;
public static final String SERVER_IP = "192.168.0.102";
public static final int SERVER_PORT = 4444;
private OnMessageReceived messageListener = null;
private boolean run = false;
public static final String LOG_TAG = "TCP";
PrintWriter out;
BufferedReader in;
public TCPclient(OnMessageReceived listener) {
messageListener = listener;
}
public void sendMessage(String message) {
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient() {
run = false;
if (out != null) {
out.flush();
out.close();
}
messageListener = null;
in = null;
out = null;
serverMessage = null;
}
public void run() {
run = true;
try {
InetAddress serverAddress = InetAddress.getByName(SERVER_IP);
Log.e(LOG_TAG, "C: Connecting...");
Socket socket = new Socket(serverAddress, SERVER_PORT);
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e(LOG_TAG, "C: Sent.");
Log.e(LOG_TAG, "C: Done.");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (run) {
serverMessage = in.readLine();
if (serverMessage != null && messageListener != null) {
messageListener.messageReceived(serverMessage);
}
//serverMessage = null;
}
Log.e(LOG_TAG, "S: Received message: '" + serverMessage + "'.");
}
catch (Exception e) {
Log.e(LOG_TAG, "S: Error", e);
}
finally {
socket.close();
}
}
catch (Exception e) {
Log.e(LOG_TAG, "C: Error", e);
}
}
public interface OnMessageReceived {
void messageReceived(String message);
}
}
Below is MainActivity.java code.
package com.example.wexfo.wifi_com;
import ...
public class MainActivity extends AppCompatActivity {
// Labels and edits
private TextView connectionText;
private EditText messageText;
private TextView chatText;
// Buttons
private ToggleButton connectButton;
private Button sendButton;
// Wifi connection
private static final String NET_SSID = "AI-THINKER";
private static final String NET_PASSWD = "aiTHINKERwifi";
private WifiConfiguration wifiConfig;
private WifiManager wifiManager;
// Other
private TCPclient tcpClient;
private void printChatLine(String text) {
chatText.append("\n>> " + text);
}
private void printChatLine(String who, String text) {
chatText.append("\n" + who + ": " + text);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionText = (TextView) findViewById(R.id.connectionText);
messageText = (EditText) findViewById(R.id.messageText);
chatText = (TextView) findViewById(R.id.chatText);
chatText.setMovementMethod(new ScrollingMovementMethod());
printChatLine("chat test");
// WiFi setup (authorization hard-coded for now)
wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + NET_SSID + "\"";
wifiConfig.preSharedKey = "\"" + NET_PASSWD + "\"";
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(wifiConfig);
connectButton = (ToggleButton) findViewById(R.id.connectButton);
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (connectButton.isChecked()) {
connectionText.setText("Disconnect WiFi");
if (!wifiManager.isWifiEnabled())
wifiManager.setWifiEnabled(true);
List<WifiConfiguration> netList = wifiManager.getConfiguredNetworks();
for (WifiConfiguration net : netList) {
if (net.SSID != null && net.SSID.equals("\"" + NET_SSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(net.networkId, true);
wifiManager.reconnect();
break;
}
}
// Start server connection thread
new ConnectTask().execute("");
}
else {
connectionText.setText("Connect WiFi");
if (wifiManager.isWifiEnabled())
wifiManager.setWifiEnabled(false);
// Stop server connection thread
if (tcpClient != null)
tcpClient.stopClient();
}
}
});
sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = messageText.getText().toString();
printChatLine("ME", message);
messageText.setText("");
// Send message to ESP
if (tcpClient != null)
tcpClient.sendMessage(message);
}
});
}
public class ConnectTask extends AsyncTask<String,String,TCPclient> {
#Override
protected TCPclient doInBackground(String... message) {
tcpClient = new TCPclient(new TCPclient.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
tcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Received message from ESP
printChatLine("ES", values[0]);
}
}
}
Now the ESP8266 is set to work as SoftAP
AT+CWMODE?
+CWMODE:3
OK
Then I make a basic setup for multiple connections and start a new server.
AT+CIPSTA="192.168.0.102"
OK
AT+CIPMUX=1
OK
AT+CIPSERVER=1,4444
OK
Here is my IP data.
AT+CIFSR
+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"1a:fe:34:8e:81:58"
+CIFSR:STAIP,"192.168.0.102"
+CIFSR:STAMAC,"18:fe:34:8e:81:58"
OK
Now when I run my app I can confirm I am connected to ESP's access point.
AT+CWLIF
192.168.4.2,00:27:15:77:82:02
OK
However there is no sign of an opened connection on the ESP and clicking SEND button does not make any data transfer. When I try to connect through ESP, I get an ERROR.
AT+CIPSTART=0,"TCP","192.168.4.2",4444
0,CLOSED
ERROR
My feeling is the app works fine but I do something horribly wrong on the ESP side and I can not figure out what it is. Maybe I have a wrong idea about the entire setup?
I have simple Java server:
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to Server side");
BufferedReader in;
PrintWriter out;
ServerSocket servers = null;
Socket fromClient = null;
// create server socket
try {
servers = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Couldn't listen to port 4444");
System.exit(-1);
}
try {
System.out.print("Waiting for a client...");
fromClient = servers.accept();
System.out.println("Client connected");
} catch (IOException e) {
System.out.println("Can't accept");
System.exit(-1);
}
in = new BufferedReader(new InputStreamReader(fromClient.getInputStream()));
out = new PrintWriter(fromClient.getOutputStream(), true);
String input;
System.out.println("Wait for messages");
while ((input = in.readLine()) != null) {
if (input.equalsIgnoreCase("exit")) break;
out.println("S ::: " + input);
System.out.println(input);
}
out.close();
in.close();
fromClient.close();
servers.close();
}
}
and simple Android client:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
new MyAsync().execute();
}
---------------------
public class MyAsync extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
try {
fromServer = new Socket("192.168.0.103",4444);
in = new BufferedReader(new InputStreamReader(fromServer.getInputStream()));
out = new PrintWriter(fromServer.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
-------------------
#Override
public void onClick(View v) {
if (v.getId() == R.id.button){
out.println(editText.getText().toString());
}
}
All work good. I send message from Android to server and sever print this message in console. But I want send Object, for example User:
public class User {
private int age;
private String fio;
public User() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFio() {
return fio;
}
public void setFio(String fio) {
this.fio = fio;
}
In Android i can write:
User user = new User();
out.print(user);
But i am not understanding that how can i read this on server side?
You can't do it with print(). Use an ObjectOutputStream.writeObject() at the sender, and ObjectInputStream.readObject() at the receiver. You will need to adjust your User class to implement Serializable and provide a private static long serialVersionUID value.
NB Don't write code like this. Code that depends on the success of code in a try block should be inside the same try block.