How to connect to PC (server) using sockets with Android app (client)? - java

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;
}
}
}

Related

Why does my service class receive null values?

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().

How to get arraylist from java to android

I'm doing an application and I need to receive an udp array from java to android and put it in a Spinner. Does anyone know how to do it?
Now, this is the code that I'm working with but I only receive a string.
Does anyone have an idea of ​​how I can receive the array working from this code?
UDPClientSocketActivity
public class UDPClientSocketActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextViewReplyFromServer;
private EditText mEditTextSendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSend = (Button) findViewById(R.id.btn_send);
mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);
buttonSend.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
sendMessage(mEditTextSendMessage.getText().toString());
break;
}
}
private void sendMessage(final String message) {
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
String stringData;
#Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
// IP Address below is the IP address of that Device where server socket is opened.
InetAddress serverAddr = InetAddress.getByName("xxx.xxx.xxx.xxx");
DatagramPacket dp;
dp = new DatagramPacket(message.getBytes(), message.length(), serverAddr, 9001);
ds.send(dp);
byte[] lMsg = new byte[1000];
dp = new DatagramPacket(lMsg, lMsg.length);
ds.receive(dp);
stringData = new String(lMsg, 0, dp.getLength());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
handler.post(new Runnable() {
#Override
public void run() {
String s = mTextViewReplyFromServer.getText().toString();
if (stringData.trim().length() != 0)
mTextViewReplyFromServer.setText(s + "\nFrom Server : " + stringData);
}
});
}
});
thread.start();
}
}
If you want to put data into Spinner there is a link: https://developer.android.com/guide/topics/ui/controls/spinner

Problems with data transmission from Android TCP Client app to ESP8266 module and vice versa

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?

Why are my client threads/listeners not receiving broadcasted messages from the server?

I made a simple prototype of a client-server application on Android
I managed to connect two clients to the server and the server can receive their messages. The problem now is that I can't seem to broadcast/receive the messages to other clients.
I try to broadcast the received message through a for loop in the Server class:
private void broadcastMessage(String message) {
for (int i = 0, j = clients.size(); i <= j; i++) {
PrintWriter out = null;
Socket socket = clients.get(i);
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// WHERE YOU ISSUE THE COMMANDS
out.println(message);
Log.d("SERVER Loop", "Broadcasting messages...");
out.close();
}
Log.d("SERVER", "Message Brodcasted");
}
This I then try to receive through a listener in the Client class :
public class ClientThreadListener implements Runnable {
protected Socket serverSocket = null;
protected String mMsgFromServer;
public ClientThreadListener(Socket serverSocket) {
this.serverSocket = serverSocket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
serverSocket.getInputStream()));
while ((mMsgFromServer = in.readLine()) != null) {
Log.d("MESSAGE FROM SERVER: ", mMsgFromServer);
handler.post(new Runnable() {
#Override
public void run() {
msgFromOtherClients.append('\n'
+ "Message From Server: " + mMsgFromServer);
}
});
}
} catch (Exception e) {
Log.e("ClientListener", "C: Error", e);
connected = false;
}
}
}
I don't get any errors or force closes though. Forgive me I know it is very messy but please bear with me and please focus on the issue at hand instead :D
Here is the full code for the Server class
public class Server extends Activity {
private TextView serverStatus;
// DEFAULT IP
public static String SERVERIP = "10.0.2.15";
// DESIGNATE A PORT
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
private String mMsgFromClient;
private MultiThreadedServer server;
private ArrayList<Socket> clients = new ArrayList<Socket>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
// SERVERIP = getLocalIpAddress();
server = new MultiThreadedServer(8080);
new Thread(server).start();
}
public class MultiThreadedServer implements Runnable {
protected int serverPort = 8080;
protected ServerSocket serverSocket = null;
protected boolean isStopped = false;
protected Thread runningThread = null;
public MultiThreadedServer(int port) {
this.serverPort = port;
}
public void run() {
synchronized (this) {
this.runningThread = Thread.currentThread();
}
openServerSocket();
while (!isStopped()) {
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
clients.add(clientSocket);
} catch (IOException e) {
if (isStopped()) {
Log.d("SERVER TEXT", "Server Stopped.");
return;
}
throw new RuntimeException(
"Error accepting client connection", e);
}
new Thread(new WorkerRunnable(clientSocket, this)).start();
}
Log.d("SERVER TEXT", "Server Stopped.");
}
private synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stop() {
this.isStopped = true;
try {
this.serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
private void broadcastMessage(String message) {
for (int i = 0, j = clients.size(); i <= j; i++) {
PrintWriter out = null;
Socket socket = clients.get(i);
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// WHERE YOU ISSUE THE COMMANDS
out.println(message);
Log.d("SERVER Loop", "Broadcasting messages...");
out.close();
}
Log.d("SERVER", "Message Brodcasted");
}
}
public class WorkerRunnable implements Runnable {
protected Socket clientSocket = null;
protected String mMsgFromClient = null;
private UUID id;
public WorkerRunnable(Socket clientSocket, MultiThreadedServer server) {
this.clientSocket = clientSocket;
id = UUID.randomUUID();
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((mMsgFromClient = in.readLine()) != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.append('\n'
+ "Message From Client ID " + getID()
+ ": " + mMsgFromClient);
}
});
}
Log.d("SERVERTEXT", "Proceed to broadcast");
server.broadcastMessage(mMsgFromClient);
} catch (IOException e) {
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
serverStatus
.append('\n'
+ "Message From Client ID "
+ getID()
+ ": "
+ "Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
private String getID() {
return id.toString();
}
}
}
Here is the full code for the Client class
public class Client extends Activity {
private EditText serverIp;
private EditText chatMsg;
private Button connectPhones;
private Button sendMsg;
private TextView msgFromOtherClients;
private String serverIpAddress = "";
private boolean connected = false;
private boolean willSendMsg = false;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
chatMsg = (EditText) findViewById(R.id.chat_msg);
sendMsg = (Button) findViewById(R.id.send_msg);
sendMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
willSendMsg = true;
}
});
msgFromOtherClients = (TextView) findViewById(R.id.msg_from_other_clients);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, Server.SERVERPORT);
connected = true;
Thread listener = new Thread(new ClientThreadListener(new Socket(serverAddr, Server.SERVERPORT)));
listener.start();
while (connected) {
if (willSendMsg) {
willSendMsg = false;
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
out.println(chatMsg.getText().toString());
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
public class ClientThreadListener implements Runnable {
protected Socket serverSocket = null;
protected String mMsgFromServer;
public ClientThreadListener(Socket serverSocket) {
this.serverSocket = serverSocket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
serverSocket.getInputStream()));
while ((mMsgFromServer = in.readLine()) != null) {
Log.d("MESSAGE FROM SERVER: ", mMsgFromServer);
handler.post(new Runnable() {
#Override
public void run() {
msgFromOtherClients.append('\n'
+ "Message From Server: " + mMsgFromServer);
}
});
}
} catch (Exception e) {
Log.e("ClientListener", "C: Error", e);
connected = false;
}
}
}
}
Your code has some issue that prevents it from working.
As already said in other answers, in your code you are closing the socket output stream right after sending the message to the client. call close() only out of your for message loop. Of course closing the socket in the client will have the same effect as closing it on the server. You must close the sockets only when client and server have finished talking. Closing it while transmitting data it's like hanging up the phone in the middle of a conversation.
Second, you create a new socket on the client side:
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, Server.SERVERPORT);
but then you pass to the listener another, newly created, socket (I suppose this is not intended):
connected = true;
Thread listener = new Thread(new ClientThreadListener(new Socket(serverAddr, Server.SERVERPORT)));
listener.start();
Third, always call flush() on an output stream right after sending data, or the data will likely not be sent (the send methods will just enqueue your data in the sending buffer).
Last (This may not be useful to you since I don't know your ultimate goal), if you need to send and receive on sockets, 90% of the time it's better and easier to do this asinchronously, using separate threads for listening and sending.
If it still doesn't work, add here some output or log trace from logcat.
You need to move the line:
server.broadcastMessage(mMsgFromClient);
inside the while:
while ((mMsgFromClient = in.readLine()) != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.append('\n'
+ "Message From Client ID " + getID()
+ ": " + mMsgFromClient);
}
});
// HERE
Log.d("SERVERTEXT", "Proceed to broadcast");
server.broadcastMessage(mMsgFromClient);
}
Otherwise, you'll only broadcast null.
EDIT: You should make sure that mMsgFromClient is not changed between posting the new Runnable and it actually executing. The best way is to initialize a field in the anonymous class with the current value, and log the value of that field instead.
EDIT2: Unless your server is supposed to close its connection to a client after sending it a broadcast message, you should use out.flush() instead of out.close() in the broadcastMessage method. It's preferrable that client connections are closed after a timeout, or just let the clients disconnect, again with a timeout.
Otherwise, your test will be very limited most of the times: a client connects and sends a message; then it receives its own message and the server closes the connection.
Please try to use AsyncTask in android which will create separate thread for communication with server.

UDP server running on android for LAN

i have server and clients running in the LAN,but my server don't accept more than one message from client app. in LAN, what code shall i put in while loop in order to accept as many messages as i send from client app ?
My server class is:
public class MainActivity extends Activity {
private Boolean shouldRestartSocketListen=true;
TextView tv1;
//MulticastLock lock;
static String UDP_BROADCAST = "UDPBroadcast";
DatagramSocket socket;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
startListenForUDPBroadcast();
// lock.release();
}
private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception {
byte[] recvBuf = new byte[15000];
if (socket == null || socket.isClosed()) {
socket = new DatagramSocket(port, broadcastIP);
//socket.setBroadcast(true);
}
//socket.setSoTimeout(1000);
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
Log.e("UDP", "Waiting for UDP broadcast");
socket.receive(packet);
String senderIP = packet.getAddress().getHostAddress();
String message = new String(packet.getData()).trim();
// Log.e("UDP", "Got UDB broadcast from " + senderIP + ", message: " + message);
tv1.setText(message);
// broadcastIntent(senderIP, message);
socket.close();
}
private void broadcastIntent(String senderIP, String message) {
Intent intent = new Intent(MainActivity.UDP_BROADCAST);
intent.putExtra("sender", senderIP);
intent.putExtra("message", message);
sendBroadcast(intent);
}
Thread UDPBroadcastThread;
void startListenForUDPBroadcast() {
UDPBroadcastThread = new Thread(new Runnable() {
public void run() {
try {
InetAddress broadcastIP = InetAddress.getByName("192.168.1.255"); //172.16.238.42 //192.168.1.255
Integer port = 11111;
while (shouldRestartSocketListen) {
listenAndWaitAndThrowIntent(broadcastIP, port);
}
//if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
} catch (Exception e) {
Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
}
}
});
UDPBroadcastThread.start();
}
void stopListen() {
shouldRestartSocketListen = false;
socket.close();
}
public void onCreate() {
};
#Override
public void onDestroy() {
stopListen();
}
public IBinder onBind(Intent intent) {
return null;
}
}
Don't close the socket unless you want to stop listening (put it outside your while loop).
I've tried using UDPFlood v2.0 from McAfee, with the socket.close() like you have it, you will miss messages as soon there are more than ~5 packets per second (depending how fast your other tasks are). The messages get buffered in your socket (OS) but you discard them by closing it.

Categories

Resources