Android Simple Client/Server Socket - java

I'm currently working on an android chat application.
First, I have created the server and then, the android client. But for some reason, the client cannot connect to the server. Nevertheless, I have specified the same port for both client and server.
Could you help me, please ?
Here is the code of my server :
public class ChatServer {
private static int port = 8080;
public static void main (String[] args) throws IOException {
ServerSocket server = new ServerSocket(port); /* start listening on the port */
System.out.println( "Listening on "+ server );
Socket client = null;
while(true) {
try {
client = server.accept();
System.out.println( "Connection from " + client );
/* start a new thread to handle this client */
Thread t = new Thread(new ClientConnect(client));
t.start();
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
System.exit(1);
server.close();
}
}
}
}
and here is the client :
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText nickname = (EditText)findViewById(R.id.nicknameField);
EditText password = (EditText)findViewById(R.id.passwordField);
Button signin = (Button) findViewById(R.id.signin);
Button signup = (Button) findViewById(R.id.signup);
new Downloader(this).execute(8080);
}
and the Asynctask class
public class Downloader extends AsyncTask<Integer, Void, Void> {
private WeakReference<MainActivity> activity;
private int port;
public Downloader(MainActivity act){
super();
activity = new WeakReference<MainActivity>(act);
}
protected Void doInBackground(Integer... params) {
port = params[0];
try {
Socket clientSocket = new Socket("localhost", port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
When I used the debugger on eclipse, it goes through the line
Socket clientSocket = new Socket("localhost", port);
but after that it goes to the IOException.
Thanks for your help !

You can go to the properties of Android on the emulator equal like you do on a smartphone Android and see the ip you go atributed.
But if you still using the Eclipse i advise you to change to Android Studio but i think you gonna have a problema with SDK you have to unnistall that but beside that no problems.

Related

I am confused and stuck when trying to connect to a channel using JSch or Socket?

So I am trying to connect to a device that is going to acquire analogue data(Red Pitaya). It has set scpi commands that control the device. I can control these through labview and using putty.
I am trying to write and android application that can access the devices scpi server and send commands to it for the device to complete.
The device is programmed in a way in that you first have to connect to the server using a SSH connection which i have no problem doing using JSch, from there you can send a command to start the scpi server and open a connection.
Now this is the bit i am struggling with and i dont understand why, when the SCPI server has started it is accessed through the Ip of the device and a raw port of 5000, but i cannot seem to write a piece of code that connects to this and performs a SCPI command. I am not to sure whether it is the connection or the way i have sent the data.
This is the code
public class rp_command extends AsyncTask<Void,Void, Void> {
String ipAddress;
int port;
String response = "";
TextView textResponse;
rp_command(String address, int rp_port, TextView textResponse){
ipAddress = address;
port = rp_port;
this.textResponse = textResponse;
}
#Override
protected Void doInBackground(Void...arg0){
Socket socket = null;
try{
socket = new Socket(ipAddress, port);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeByte(1);
out.writeUTF("DIG:PIN LED2,1");
out.flush();
} catch (UnknownHostException e){
e.printStackTrace();
response = "UnknownHostException:" + e.toString();
} catch (IOException e){
e.printStackTrace();
response = "IOException:" + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}return null;
}
#Override
protected void onPostExecute(Void result){
textResponse.setText(response);
super.onPostExecute(result);
}
}
If anyone has any advice it would be appreciated
thanks
Got it working here i believe the issue was due to not ending a command with \r\n being at the end of the string here is the working test code if anyone is interested. This is for sending a string not receiving.
public class MainActivity extends AppCompatActivity {
Socket s = new Socket();
PrintWriter s_out;
BufferedReader s_in;
String out = null;
public void sendCommand (String command){
try {
s_out = new PrintWriter(s.getOutputStream(), true);
s_out.println(command);
}catch (IOException e){
System.out.println(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button LED_ON, LED_OFF;
LED_ON = (Button)findViewById(R.id.button);
LED_OFF = (Button)findViewById(R.id.button2);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
s.connect(new InetSocketAddress("192.168.0.104", 5000));
}catch (IOException e){
System.out.println(e);
}
LED_ON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendCommand("DIG:PIN LED2,1\r\n");
}
});
LED_OFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendCommand("DIG:PIN LED2,0\r\n");
}
});
}
}
When using buttons to initiate a command i noticed that if you write the send command code in there instead of a separate function the app would time out and crash.

Android and java bluetooth client server app

I have an android app. I want to send a string to java server when I touch the button each time in my client app.I am able to connect to server.
But the problem is when I touch the button, no string is sending to server. No matter how many times I touch the button the string is not sending but suddenly when I exit the app in my smartphone, means when I destroy the activity, all the strings then transfers to the server at the same time.
If I touch the button 100 times, 100 same strings are transferred to the server only when I destroy activity. I want the string to be transferred to server at the time when I touch the button.
Please help me with this. I am a newbie. My code is below:
public class Joystick extends Activity {
BluetoothAdapter ba=BluetoothAdapter.getDefaultAdapter();
//local bluetooth adapter object created
BluetoothDevice bd; //GLOBAL DECLARATION BLOCK
BluetoothSocket bs;
OutputStream os;
InputStream in;
Button up;
private static final UUID MY_UUID =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.joystick);
up= (Button) findViewById(R.id.up);
if(ba.isEnabled()==false) //BLUETOOTH ADAPTER ENABLED IF WAS DISABLED
ba.enable();
final String address = getIntent().getStringExtra("address").trim();
setResult(100, new Intent());
bd=ba.getRemoteDevice(address);
BluetoothConnect.start();
}
#Override
protected void onResume(){
super.onResume();
up.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
try {
os = bs.getOutputStream();
String message = "up";
byte[] msgBuffer = message.getBytes();
os.write(msgBuffer);
} catch (IOException e) {
e.printStackTrace();
}
break;
case MotionEvent.ACTION_UP:
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
return true;
}
});
}
Thread BluetoothConnect = new Thread(){
public void run(){
try {
bs=bd.createRfcommSocketToServiceRecord(MY_UUID);
bs.connect();
} catch (IOException e) {
try {
bs.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
};
protected void onStop(){
super.onStop();
try {
os.close();
bs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (os != null) {
try {
os.flush();
} catch (IOException e) {
}
}
}}
the server code is:
public class SimpleSPPServer {
private static Robot robot;
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=SampleSPPServer";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: "+dev.getBluetoothAddress());
System.out.println("Remote device name: "+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
try{
robot=new Robot();
if(lineRead.equalsIgnoreCase("up")){
robot.keyPress(KeyEvent.VK_UP);
robot.keyRelease(KeyEvent.VK_UP);
} }
catch(AWTException e){
System.out.println("exception while creating robot instance");
}
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write("Response String from SPP Server\r\n");
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
SimpleSPPServer sampleSPPServer=new SimpleSPPServer();
sampleSPPServer.startServer();
}
}
Problem solved.. Just add "\n" at the end of string you want to transfer.

How send String message to server from Android with Socket.IO-client Java?

I use socket.io-client-java library
I have android client and Java server
Server code:
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to Server side");
BufferedReader in = null;
PrintWriter out = null;
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, output;
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 client:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Socket mSocket = null;
private Button button;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
mSocket.connect();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button){
mSocket.emit("new message", "Some message");
}
}
}
And if I tried connect to server I get this:
Welcome to Server side
Waiting for a client...Client connected
Wait for messages
GET /socket.io/?EIO=3&transport=polling HTTP/1.1
User-Agent: Dalvik/1.4.0 (Linux; U; Android 2.3.7; Android SDK built for x86 Build/GINGERBREAD)
Host: 10.0.2.2:4444
Connection: Keep-Alive
Accept-Encoding: gzip
But when I tried to send String message
mSocket.emit("new message", "Some message");
Nothing happens. I send the wrong or server is wrong?
To properly init socket.io client, you need to do something like this:
Socket _socket = IO.socket(SERVER_URI);
_socket.on(Socket.EVENT_CONNECT, _onConnectionListener)
.on(Socket.EVENT_DISCONNECT, _onDisconnectListener)
.on(Socket.EVENT_CONNECT_ERROR, _onConnectionErrorListener)
.on(Socket.EVENT_MESSAGE, _onMessageReceivedListener)
.on(CHAT_MESSAGE_PUBLISH, _onMessageReceivedListener);
Each of listeners is run when the event takes place, e.g.:
private Emitter.Listener _onMessageReceivedListener = new Emitter.Listener() {
#Override
public void call(Object... args) {
JSONArray jsonArray = (JSONArray) args[0];
if (jsonArray != null && jsonArray.length() > 0) {
Gson gson = new Gson();
List<MessageModel> historyList = gson.fromJson(jsonArray.toString(), listType);
loadReceivedMessage(historyList);
chatLoging(jsonArray.toString());
}
}
};
The call() method will be triggered when you a receive new message from the server.

Android 2-Way TCP/IP ServerSocket/Socket Communication

Using this great tutorial by the Java Code Geeks, I am easily able to create a client activity that sends data via TCP to a server's port 4000 using the following code:
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Then using their other snippet for the server activity I can catch messages using TCP on that port:
public class Server extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
My question is how can I make it so these 2 can communicate back and forth?
Android -> Server(4000) -> Android(4001)?
In other words how can I make my app help the device act as both the client (sending out data to another device on port 4000) and the server (listening for data on port 4001) at the same time?
On the Server side change the port to 5000 (same as Client) instead of 6000:
And you need to update the following class because you don't want to create a new socket, you should use the one already created (in the Client part).
NB: the socket given as an argument to CommunicationThread is the socket that you supposedly already created (Client part).
class ServerThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
}
}

turn my TCP android application to jar

I've built a TCP server and now I would like to turn it into a jar so I can use it in many different app. So basically later on I'd like to just include it in other projects. if it was just a list of functions I could figure it out but it's not I'm so I'm not sure. I thought about making it all just one function but it wouldn't run, when I called the function the app would just fail.
Also I hope other people can find this server code useful for their own projects
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
public String serverIP = "127.0.0.1";
private InetAddress serverAddr;
public static final int SERVERPORT = 4444;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Categories

Resources