Android Studio tcp client connect to c# server - java

i started with android a short time ago. This time i tried to connect a c# tcp server with a java tcp client. To debug i worte a c# client and server and if i use the c# client to talk to the server, there is no problem. But my java socket has problems with connecting. I copied the java tcp code for example from the net.
c# code:
namespace MTCliserv2
{
class MTCliserv2
{
static void Main(string[] args)
{
string txt;
Console.Write("MTCliserv2 Server or Client (s/c): ");
txt = Console.ReadLine();
if (txt == "s")
Server();
else
Client();
Console.Write("\nHit any Key to continue "); Console.ReadKey();
}
static IPAddress GetIPAddress()
{
IPAddress ipAdr = Dns.Resolve("localhost").AddressList[0];
ipAdr = IPAddress.Parse("192.168.1.1");
return ipAdr;
}
static void Server()
{
TcpListener server;
Socket socke;
IPAddress ipAdr = GetIPAddress();
try
{
server = new TcpListener(ipAdr, 13);
server.Start();
Console.WriteLine("Server {0} gestartet", server.LocalEndpoint);
while (true)
{
socke = server.AcceptSocket(); // Aufruf blockiert!!
mit diesem Client abwickelt
new ConnTalk(socke);
}
}
catch (Exception e)
{
Console.WriteLine("Error {0}", e);
}
}
static void PrintConnectionInfo(Socket aSock)
{
Console.WriteLine("Anfrage von {0}", aSock.RemoteEndPoint);
}
static void Client()
{
const string serverName = "localhost";
try
{
TcpClient client = new TcpClient("192.168.1.1", 13);
NetworkStream strm = client.GetStream();
Socket sc = client.Client;
StreamReader strmRd = new StreamReader(strm);
StreamWriter strmWr = new StreamWriter(strm);
string txt, txt2;
Console.WriteLine("Connected to {0}", sc.RemoteEndPoint);
while (true)
{
Console.Write("Msg= ");
txt = Console.ReadLine();
if (txt == "end")
break;
strmWr.WriteLine(txt); strmWr.Flush();
txt2 = strmRd.ReadLine();
Console.WriteLine("Answer: {0}", txt2);
}
client.Close(); strmRd.Close(); strmWr.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
// Pro Verbindung wird 1 ConnTalk-objekt erzeugt
class ConnTalk
{
Thread m_Thr;
Socket m_Sc;
public ConnTalk(Socket aSc)
{
m_Sc = aSc;
m_Thr = new Thread(this.TalkWithClient);
m_Thr.Start();
}
void TalkWithClient()
{
NetworkStream strm = new NetworkStream(m_Sc);
StreamReader strmRd = new StreamReader(strm);
StreamWriter strmWr = new StreamWriter(strm);
string txt;
Console.WriteLine("Talking with {0}", m_Sc.RemoteEndPoint);
try
{
while (true)
{
txt = strmRd.ReadLine();
Console.WriteLine("Msg: {0}", txt);
txt += " Echo!! \r\n";
strmWr.Write(txt); strmWr.Flush();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception in TalkWithClient");
}
Console.WriteLine("{0} Disconnected", m_Sc.RemoteEndPoint);
m_Sc.Close(); strm.Close(); strmRd.Close(); strmWr.Close();
return;
}
}
}
And here is the java code:
package com.example.mogri.tcpsocket;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText ettext;
private TextView tvlog;
TcpClient mTcpClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ( ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.INTERNET},225);
}
if ( ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE},225);
}
ettext = (EditText) findViewById(R.id.etText);
tvlog = (TextView) findViewById(R.id.tVlog);
Button btnsend = (Button) findViewById(R.id.btnsend);
btnsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String input = ettext.getText().toString();
mTcpClient.sendMessage(input);
log(input);
}
});
new ConnectTask().execute("");
}
public void log(String add){
tvlog.setText( tvlog.getText()+"\n"+add);
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//response received from server
Log.d("test", "response " + values[0]);
//process server response here....
}
}
}
The tcpclient class:
package com.example.mogri.tcpsocket;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
* Created by mogri on 01.04.2017.
*/
public class TcpClient {
public static final String SERVER_IP = "192.168.1.1"; //server IP address
public static final int SERVER_PORT = 13;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
/**
* Close the connection and release the members
*/
public void stopClient() {
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}

Related

Using TCP to communicate between an Android and microcontroller

I'm attempting to use a TCP connection to communicate between my Android phone and a microcontroller (a Particle Photon, very similar to an Arduino), where the phone is a wireless hotspot not connected to the internet.
Whenever I attempt to get them to connect to one another, I can get the client (Android app) to connect to the server (Photon). The TCPClient helper class seems to get stuck at
serverMessage = in.readLine();
in the TCPClient helper class. This is my debug result:
E/TCP Client: C: Connecting...
E/TCP Client: C: out2 = java.io.OutputStreamWriter#ca4d31b
E/TCP Client: C: out1 = java.io.BufferedWriter#3c624cb8
E/TCP Client: C: out0 = java.io.PrintWriter#378aea91
E/TCP Client: C: Sent.
E/TCP Client: C: Done.
E/TCP Client: C: received = java.io.BufferedReader#36c43df6
E/TCP Client: C: run = true
E/TCP Client: C: I got to the while loop!
So it seems pretty clear where the helper class breaks down at in.readLine(). What needs to happen for the code to progress through the line and show the received result?
This is the TCPClient.java:
import android.util.Log;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TCPClient {
private String serverMessage;
public static final String SERVERIP = "192.168.43.157"; //your Photon (formerly computer) IP address
public static final int SERVERPORT = 23;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedWriter out1;
OutputStreamWriter out2;
BufferedReader in;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TCPClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
* #param message text entered by client
*/
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient(){
mRun = false;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out2 = new OutputStreamWriter(socket.getOutputStream());
out1 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: out2 = " + out2);
Log.e("TCP Client", "C: out1 = " + out1);
Log.e("TCP Client", "C: out0 = " + out);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
//receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.e("TCP Client", "C: received = " + in);
Log.e("TCP Client", "C: run = " + mRun);
//in this while the client listens for the messages sent by the server
while (mRun) {
Log.e("TCP Client", "C: I got to the while loop!");
serverMessage = in.readLine();
Log.e("TCP Client", "C: serverMessage = " + serverMessage);
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
} else {
serverMessage = null;
}
}
Log.e("TCP Client", "C: run = " + mRun);
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
For completeness, this is my Photon firmware:
SYSTEM_MODE(MANUAL);
TCPServer server = TCPServer(23);
TCPClient client;
int flag = 0;
void setup() {
WiFi.on();
WiFi.setCredentials("AndroidAP", "password");
WiFi.connect();
// Make sure your Serial Terminal app is closed before powering your device
Serial.begin(9600);
// Now open your Serial Terminal, and hit any key to continue!
// start listening for clients
server.begin();
}
void loop() {
if (client.connected()) {
if(flag == 0) {
server.write("200");
// Serial.println("200");
flag = 0;
Serial.println(WiFi.SSID());
Serial.println(WiFi.localIP());
delay(1000);
}
// echo all available bytes back to the client
while (client.available() > 0) {
server.write("200");
Serial.println("200");
}
} else {
// if no client is yet connected, check for a new connection
client = server.available();
}
}
This is my MainActivity.java:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private TCPClient mTcpClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.send_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// connect to the server
new connectTask().execute("message1");
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
Log.d("Message", message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("values", values[0]);
}
}
}
For anyone else who comes along and is looking to do something similar, I eventually got this code to work.
TCPClient.java
import android.util.Log;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import static android.R.id.message;
public class TCPClient {
private String serverMessage;
public static String buttonPushed;
public static final String SERVERIP = "192.168.43.157"; //your Photon (formerly computer) IP address
public static final int SERVERPORT = 23;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedWriter out1;
OutputStreamWriter out2;
OutputStream out3;
BufferedReader in;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TCPClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
* #param message text entered by client
*/
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
Log.d("TCP Client", "Message: " + message);
out.flush();
}
}
public void stopClient(){
mRun = false;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out3 = socket.getOutputStream();
out2 = new OutputStreamWriter(socket.getOutputStream());
out1 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: out3 = " + out3);
Log.e("TCP Client", "C: out2 = " + out2);
Log.e("TCP Client", "C: out1 = " + out1);
Log.e("TCP Client", "C: out0 = " + out);
sendMessage(buttonPushed); //this was the key
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
//receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.e("TCP Client", "C: received = " + in);
Log.e("TCP Client", "C: run = " + mRun);
//in this while the client listens for the messages sent by the server
while (mRun) {
Log.e("TCP Client", "C: I got to the while loop!");
serverMessage = in.readLine();
Log.e("TCP Client", "C: serverMessage = " + serverMessage);
new TCPClient(mMessageListener);
stopClient();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
} else {
serverMessage = null;
}
}
Log.e("TCP Client", "C: run = " + mRun);
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
Log.d("TCP Client", "Socket closed.");
serverMessage = null;
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// private ListView mList;
// private ArrayList<String> arrayList;
// private MyCustomAdapter mAdapter;
private TCPClient mTcpClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.send_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// connect to the server
TCPClient.buttonPushed = "Get range 1";
new connectTask().execute("");
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
Log.d("Message", message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("values", values[0]);
//in the arrayList we add the messaged received from server
// arrayList.add(values[0]);
// notify the adapter that the data set has changed. This means that new message received
// from server was added to the list
// mAdapter.notifyDataSetChanged();
}
}
}
Photon code:
SYSTEM_MODE(MANUAL);
TCPServer server = TCPServer(23);
TCPClient client;
void setup() {
WiFi.on();
WiFi.setCredentials("AndroidAP", "password");
WiFi.connect();
// Make sure your Serial Terminal app is closed before powering your device
Serial.begin(9600);
// Now open your Serial Terminal, and hit any key to continue!
// start listening for clients
server.begin();
}
void loop() {
if (client.connected()) {
// echo all available bytes back to the client
while (client.available() > 0) {
server.write("200\n");
Serial.println("200");
Serial.println(WiFi.SSID());
Serial.println(WiFi.localIP());
}
} else {
// if no client is yet connected, check for a new connection
client = server.available();
}
}

Multiple client server android

I'm doing a desktop server application in java with multiple android clients, each one with a thread. I'm using sockets to provide the communication.
Until now, clients are sending messages to the server and then do something based on server response.
But now I need that server send a message to a specific client and I don't know how.
Could you help me please?
Thanks
Server class
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException{
boolean listening = true;
try (ServerSocket serverSocket = new ServerSocket(4444)){
while(listening){
new ServerThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
}
}
ServerThread
import java.net.*;
import java.io.*;
public class ServerThread extends Thread {
private Socket socket = null;
public ServerThread(Socket socket) {
super("ServerThread");
this.socket = socket;
}
public void run() {
try (
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
) {
String inputLine, outputLine;
GameProtocol gp = new GameProtocol();
outputLine = gp.processInput(null);
//System.out.println(outputLine);
//out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
//System.out.println(outputLine);
outputLine = gp.processInput(inputLine);
System.out.println(outputLine);
out.println(outputLine);
if (outputLine.equals("Bye"))
break;
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TcpClient class
import android.util.Log;
import java.io.*;
import java.net.*;
/**
* Created by andrecorreia on 03/06/16.
*/
public class TcpClient {
public static final String SERVER_IP = "10.0.2.2"; // computer IP address
public static final int SERVER_PORT = 4444;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
*
* #param message text entered by client
*/
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
/**
* Close the connection and release the members
*/
public void stopClient() {
Log.i("Debug", "stopClient");
// send mesage that we are closing the connection
//sendMessage(Constants.CLOSED_CONNECTION + "Kazy");
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
//InetAddress serverAddr = InetAddress.getLocalHost();
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket("192.168.1.92", SERVER_PORT);
try {
Log.i("Debug", "inside try catch");
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// send login name
//sendMessage(Constants.LOGIN_NAME + PreferencesManager.getInstance().getUserName());
//sendMessage("Hi");
//in this while the client listens for the messages sent by the server
while (mRun) {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
Main Activity
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
public static TcpClient tcpClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ConnectTask().execute("");
// Set up click listeners for all the buttons
View playNowButton = findViewById(R.id.playNow_button);
playNowButton.setOnClickListener(this);
View optionsButton = findViewById(R.id.options_button);
optionsButton.setOnClickListener(this);
View helpButton = findViewById(R.id.help_button);
helpButton.setOnClickListener(this);
View exitButton = findViewById(R.id.exit_button);
exitButton.setOnClickListener(this);
//---------------------------------------------
}
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.playNow_button:
i = new Intent(this, PlayNowActivity.class);
startActivity(i);
break;
case R.id.options_button:
i = new Intent(this, OptionsActivity.class);
tcpClient.sendMessage("options");
startActivity(i);
break;
case R.id.help_button:
i = new Intent(this, HelpActivity.class);
tcpClient.sendMessage("help");
startActivity(i);
break;
case R.id.exit_button:
finish();
break;
}
}
public class ConnectTask extends AsyncTask<String,String,TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object and
tcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
tcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
/*View view = adapter.getChildView(0, 0, false, null, null);
TextView text = (TextView) view.findViewById(R.id.betChildOdd);
child2.get(0).get(0).put("OLD", text.getText().toString());
child2.get(0).get(0).put(CONVERTED_ODDS, values[0].toString());
child2.get(0).get(0).put("CHANGE", "TRUE");
adapter.notifyDataSetChanged();*/
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The solution you suggested could be something like this?
Thanks
public class Server {
private static ArrayList<ServerThread> playerList;
private static LinkedBlockingQueue<Object> messages;
private static GameProtocol gp ;
public static void main(String[] args) throws IOException{
playerList = new ArrayList<ServerThread>();
messages = new LinkedBlockingQueue<Object>();
gp = new GameProtocol();
Thread accept = new Thread() {
public void run(){
while(true){
try{
ServerSocket serverSocket = new ServerSocket(4444);
ServerThread player = new ServerThread(serverSocket.accept(), gp);
playerList.add(player);
player.start();
}
catch(IOException e){ e.printStackTrace(); }
}
}
};
accept.setDaemon(true);
accept.start();
Thread messageHandling = new Thread() {
public void run(){
while(true){
try{
Object message = messages.take();
// Do some handling here...
System.out.println("Message Received: " + message);
}
catch(InterruptedException e){ }
}
}
};
messageHandling.setDaemon(true);
messageHandling.start();
}
}

android client-java server communication

We are developing an android application.It basically involves client server communication.Client is android phone and server is java.Client and server communication takes place.It is expected that client sends a message to the server and server responds back to the client.But in reality client is able to send the message to the server but server is unable or sends an incorrect response.I don't understand why is it happening.
Here is the client code(android):
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
public TextView accept;
private Button button;
private String message;
private static BufferedReader bufferedReader;
public static InputStreamReader inputStreamReader;
String response;
DataInputStream dis;
static String Extra_message = "hkrw.clientside";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textField = (EditText) findViewById(R.id.editText1);
button = (Button) findViewById(R.id.button1);
this.accept = (TextView) findViewById(R.id.accept);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
message = textField.getText().toString();
textField.setText("");
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
accept.setText(response);
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
DataOutputStream dataOutputStream = null;
DataInputStream smalldataInputStream = null;
try {
client = new Socket("192.168.1.6", 4446);
printwriter = new PrintWriter(client.getOutputStream(), true);
inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
printwriter.write(message);
// smalldataInputStream = new DataInputStream(client.getInputStream());
printwriter.flush();
printwriter.close();
//dis= new DataInputStream(client.getInputStream());
//response=dis.readUTF();
response = bufferedReader.toString();
client.getInputStream();
// client.shutdownInput();
// client.shutdownOutput();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the code of the new activity which I have created in client side.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class respond extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_respond);
Intent intent=getIntent();
String message = intent.getStringExtra(MainActivity.Extra_message);
TextView response;
response= (TextView) findViewById(R.id.textView1);
response.setText(message);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_respond, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the server code in java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.DataOutputStream;
public class Server {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static PrintWriter printwriter ;
static DataOutputStream dos;
public static void main(String[] args) {
String w="Hello World";
try {
serverSocket = new ServerSocket(4446); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4446");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println(message);
dos=new DataOutputStream(clientSocket.getOutputStream());
dos.writeUTF(w);
clientSocket.close();
System.out.println(dos);
inputStreamReader.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
this example sends a message to the server (pc in wlan),
and then gets the message back from server to phone, changing text accordingly.
change ip address of server to your pc address in wlan,
make sure to start server first, then phone app, being in that wlan
Server:
public class ChatServer implements Runnable{
private Socket socket = null;
private ServerSocket server = null;
private Thread thread = null;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;
int port;
boolean done ;
public ChatServer(){
port = 6668;
try{
System.out.println("Gewählter Port: " + port + ", bitte warte...");
server = new ServerSocket(port);
System.out.println("Server gestartet: " + server);
start();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
public void start(){
if (thread == null){
thread = new Thread(this);
thread.start();
}
}
public void run(){
while (thread != null){
try{
System.out.println("waiting for Client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket + " IP: "+ socket.getInetAddress());
System.out.println("connecting ...");
open();
done = false;
while (!done){
try{
String line = streamIn.readUTF();
System.out.println(line);
send("Server recieved :"+line);
done = line.equals(".bye");
}
catch(IOException ioe){
done = true;
ioe.printStackTrace();
}
}
close();
}
catch(IOException ie){
System.out.println("Acceptance Error: " + ie);
}
}
}
public void send(String msg)
{
try
{
if(msg != null) {
streamOut.writeUTF(msg);
streamOut.flush();
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public void open() throws IOException{
streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void close() throws IOException{
if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
if (streamOut != null) streamOut.close();
}
#SuppressWarnings("deprecation")
public void stop(){
if (thread != null){
thread.stop();
thread = null;
}
}
}
client:
public class MainActivity extends Activity implements Runnable{
EditText textUnten;
Button button;
ChatProzKlasse chat;
public static String puffer;
public static String messages;
public static TextView textMitte;
Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textMitte = (TextView) findViewById (R.id.textMitteID);
textUnten = (EditText) findViewById (R.id.textUntenID);
button = (Button) findViewById(R.id.sendButton);
messages = "";
chat = new ChatProzKlasse();
thread = new Thread(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chat.client.send(textUnten.getText().toString());
textUnten.setText("");
}
});
thread.start();
}
public void setTextMitte(){
runOnUiThread(new Runnable() {
#Override
public void run() {
textMitte.setText(messages);
}
});
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void run() {
while(true) {
setTextMitte();
try {
thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ChatClient {
private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
private DataInputStream streamIn = null;
public static boolean isconnected = false;
public ChatClient(String serverName, int serverPort){
System.out.println("Verbindungsaufbau. Bitte warten ...");
try{
socket = new Socket(serverName, serverPort);
Log.d("DEBUG", "Connected: " + socket);
if(socket != null) {
start();
}
}
catch(UnknownHostException uhe){
Log.d("DEBUG","Host unknown: " + uhe.getMessage());
}
catch(IOException ioe){
Log.d("DEBUG","Unexpected exception: " + ioe.getMessage());
}
}
public void start() throws IOException
{
console = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
isconnected = true;
}
public void stop(){
try{
if (console != null) console.close();
if (streamOut != null) streamOut.close();
if (socket != null) socket.close();
}
catch(IOException ioe){
System.out.println("Error closing ...");
}
}
public void open() throws IOException{
streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException{
if (socket != null) socket.close();
if (console != null) console.close();
}
public void send(String msg)
{
try
{
if(msg != null) {
streamOut.writeUTF(msg);
streamOut.flush();
}
}
catch(IOException ioe)
{
Log.d("DEBUG","Sending error: " + ioe.getMessage());
}
}
public void recieve(){
try{
open();
boolean done = false;
while (!done){
try{
String line = streamIn.readUTF();
if(!(line.equals(""))) {
MainActivity.messages =line;
MainActivity.puffer = line;
}
System.out.println(" " + line);
done = line.equals(".bye");
}
catch(IOException ioe){
done = true;
ioe.printStackTrace();
}
}
close();
}
catch(IOException ie){
System.out.println("Acceptance Error: " + ie);
}
}
}
public class ChatProzKlasse implements Runnable {
Thread thread;
ChatClient client;
public ChatProzKlasse(){
thread = new Thread(this);
thread.start();
}
#Override
public synchronized void run() {
if(client == null) {
try {
System.out.println(" trying new Client");
client = new ChatClient("192.168.1.111", 6668);
} catch (Exception e) {
e.printStackTrace();
}
}
if (client !=null){
if(client != null && ChatClient.isconnected) {
client.recieve();
}
}
}}

Socket from Server (java app) to Android app

I have a problem, and I don´t know if it´s possible.
I have an Android app that are a client socket.
This is the code to send a message to a server in Android App:
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
System.out.println("envia mensaje");
client = new Socket("ip of server", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
At same time, in Android App, a socket is created in 4445 port:
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 4445;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println(message);
}
});
/*SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();*/
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And this is the server code, that create a socket in 4444 port:
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println("Dirección entrante"+clientSocket.getInetAddress());
//System.out.println("Dirección entrante2"+clientSocket.get());
System.out.println(message);
ip_a = clientSocket.getInetAddress().toString().substring(clientSocket.getInetAddress().toString().indexOf("/")+1, clientSocket.getInetAddress().toString().length());
//message.substring(message.indexOf(":")+1, message.length()).trim();
System.out.println("realiza conexión a ip:#"+ip_a+"#");
messsage = "enviado desde el servidor"; // get the text message on the text field
SendMessage(ip_a);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
This work correctly, but I want send a message from server to a Android device throug IP that socket have.
I try with clientSocket.getInetAddress(), and with clientSocket.getRemoteSocketAddress(), but not work. I create a socket in Android app in 4445 port, but the server can´t connect to socket of android app.
Can you help me?
Thanks in advance
Ok, I will try.
This is my server aplication:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class SimpleTextServer {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static Socket client;
private static String messsage;
private static PrintWriter printwriter;
static String ip_a;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
System.out.println("Server started. Listening to the port 4444:"+getIpAddress());
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
System.out.println("Dirección entrante"+clientSocket.getInetAddress());
//System.out.println("Dirección entrante2"+clientSocket.get());
System.out.println(message);
ip_a = clientSocket.getInetAddress().toString().substring(clientSocket.getInetAddress().toString().indexOf("/")+1, clientSocket.getInetAddress().toString().length());
//message.substring(message.indexOf(":")+1, message.length()).trim();
System.out.println("realiza conexión a ip:#"+ip_a+"#");
messsage = "enviado desde el servidor"; // get the text message on the text field
SendMessage(ip_a);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
public static void SendMessage(String ip) {
try {
System.out.println("comienza a enviar mensaje");
client = new Socket(ip, 4445); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
And this is my activity in my Android app:
package com.lakj.comspace.simpletextclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SlimpleTextClientActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
//ServerSocket serverSocket;
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slimple_text_client);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
System.out.println("IP DE CLIENTE EMULADOR: "+getIpAddress());
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
//myClientTask.execute();
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("ENVIA MENSAJE BOTON");
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
System.out.println("envia mensaje");
client = new Socket("ip de servidor", 4444); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.slimple_text_client, menu);
return true;
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 4445;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n";
SlimpleTextClientActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println(message);
}
});
/*SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();*/
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
If I run the android app, the message is sended to server, and server show it.
But, the server can´t connect to Android. The IP is unracheable. I don´t know why...

how can i send my message from android client to other android client using my socket java PC server

i have my code that sucessfuly send my client message to server.. can anyone help pls ? i'm new in socket programming. i want to establish a server that sends the message of my android client to other android client... here is my code
CLIENT ANDROID :
package com.example.websocketclient;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Chatroom extends Activity {
public static String msgToServer = null;
TextView uname;
EditText in;
Button snd;
TextView out;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatroom);
uname = (TextView) findViewById(R.id.textViewmynam);
in = (EditText) findViewById(R.id.editTextInput);
snd = (Button) findViewById(R.id.buttonSend);
out = (TextView) findViewById(R.id.textViewOutput);
Bundle bundle = getIntent().getExtras();
String urname = bundle.getString("myname");
uname.setText(urname);
MyClientTask clientTask = new MyClientTask();
clientTask.execute();
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
connect();
return null;
}
}
public void connect() {
Socket sock;
int[] allports = {1111,1919,2020};
int portnum;
for(int i=1;i<allports.length;i++) {
try {
portnum = allports[i];
boolean socketno = Middleware.available(portnum);
String ad = "192.168.149.1";
if(socketno = true) {
sock = new Socket(ad,portnum);
while(socketno) {
sendmsg(sock);
}//while
// sock.close();
}//if
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendmsg (final Socket s) {
snd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//boolean listening = true;
String inmsg = ""+in.getText().toString();
String response = "";
msgToServer = inmsg;
//out.append("you:"+msgToServer+"\n");
try {
DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());
DataInputStream inToServer = new DataInputStream(s.getInputStream());
if(outToServer != null){
outToServer.writeBytes(msgToServer+"\n");
}
}
catch (Exception e) {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chatroom, menu);
return true;
}
}
Here is my PC Server side :
package Server;
import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
public class SocketServer extends Thread {
final static int _portNumber = 1919; //Arbitrary port number
public static void main(String[] args)
{
try {
new SocketServer().startServer();
} catch (Exception e) {
System.out.println("I/O failure: " + e.getMessage());
}
}
public void startServer() throws Exception {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(_portNumber);
} catch (IOException e) {
System.err.println("Could not listen on port: " + _portNumber);
System.exit(-1);
}
while (listening) {
System.out.println("Huwat huwat kang client..!");
handleClientRequest(serverSocket);
}
serverSocket.close();
}
private void handleClientRequest(ServerSocket serverSocket) {
try {
new Thread(new ConnectionRequestHandler(serverSocket.accept())).start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Handles client connection requests.
*/
public class ConnectionRequestHandler implements Runnable{
private Socket _socket;
private PrintWriter _out;
private BufferedReader _in;
public ConnectionRequestHandler(Socket socket) {
_socket = socket;
}
public void run() {
String info;
int maxid;
System.out.println("Client connected to socket: " + _socket.toString());
info = _socket.toString();
//incrementing the msg_id
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
_socket.getOutputStream()));
_in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
String inputLine;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/finalclient","root","");
PreparedStatement st = con.prepareStatement("select *from msgs order by msg_id desc");
ResultSet r1 = st.executeQuery();
r1.first(); // or r1.next()
maxid = r1.getInt("msg_id") + 1;
while ((inputLine = _in.readLine()) != null) {
System.out.println("Message from Client: "+inputLine);
out.write(inputLine);
try {
PreparedStatement st1=con.prepareStatement("insert into msgs values(?,?,?)");
st1.setInt(1,maxid);
st1.setString(2,info);
st1.setString(3,inputLine);
int count = st1.executeUpdate ();
System.out.println (count + " rows were inserted to Database");
}
catch (Exception e) {
System.out.println("Failed to Insert from DB"+e);
}
}
}
catch (Exception e) {
System.out.println("Failed to Select from DB"+e);
}
}
}
}

Categories