I'm developing an Android application (client) and want it to connect with my Java server using TCP communication.
I've done the code - simple program, client send a message and server echos it back - as below:
Server code:
import java.net.*;
public class Server {
public static void main(String[] args) {
int nreq = 1;
try
{
ServerSocket sock = new ServerSocket (8080);
for (;;)
{
Socket newsock = sock.accept();
System.out.println("Creating thread ...");
Thread t = new ThreadHandler(newsock,nreq);
t.start();
}
}
catch (Exception e)
{
System.out.println("IO error " + e);
}
System.out.println("End!");
}
}
a Thread Handler code in the same project file of the server:
import java.io.*;
import java.net.*;
class ThreadHandler extends Thread {
Socket newsock;
int n;
ThreadHandler(Socket s, int v) {
newsock = s;
n = v;
}
public void run() {
try {
PrintWriter outp = new PrintWriter(newsock.getOutputStream(), true);
BufferedReader inp = new BufferedReader(new InputStreamReader(
newsock.getInputStream()));
outp.println("Hello :: enter QUIT to exit \n");
boolean more_data = true;
String line;
while (more_data) {
line = inp.readLine();
System.out.println("Message '" + line + "' echoed back to client.");
if (line == null) {
System.out.println("line = null");
more_data = false;
} else {
outp.println("From server: " + line + ". \n");
if (line.trim().equals("QUIT"))
more_data = false;
}
}
newsock.close();
System.out.println("Disconnected from client number: " + n);
} catch (Exception e) {
System.out.println("IO error " + e);
}
}
}
And this is the Client side (Android):
package com.android.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Client extends Activity {
/** Called when the activity is first created. */
Scanner scanner = new Scanner(System.in);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText msg = (EditText) findViewById(R.id.etMsg);
Button send = (Button) findViewById(R.id.bSend);
final TextView convo = (TextView) findViewById(R.id.tvConvo);
final TextView status = (TextView) findViewById(R.id.tvStatus);
try {
send.setOnClickListener(new View.OnClickListener() {
Socket s = new Socket("localhost", 8080);
String message = msg.getText().toString();
#Override
public void onClick(View v) {
status.setText("...");
PrintWriter outp = null;
BufferedReader inp = null;
status.setText("Established connection..");
String serverMsg = null;
try {
outp = new PrintWriter(s.getOutputStream(), true);
inp = new BufferedReader(new InputStreamReader(s.getInputStream()));
serverMsg = inp.readLine();
} catch (IOException e) {
e.printStackTrace();
}
convo.append(serverMsg + "\n");
if (message != null) {
if (msg.getText().toString().trim() == "QUIT") {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
status.setText("Disconnected from server.");
} else {
try {
convo.append(message + "\n");
outp.println(message);
serverMsg = inp.readLine();
convo.append(serverMsg + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
else
status.setText("Problem in connection..!");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the XML file:
<?xml version="1.0" encoding="utf-8" ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<TextView android:id="#+id/tvText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Your message here:" />
- <EditText android:id="#+id/etMsg" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10">
<requestFocus />
</EditText>
<TextView android:id="#+id/tvStatus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Status..." android:textAppearance="?android:attr/textAppearanceSmall" />
<Button android:id="#+id/bSend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" />
<TextView android:id="#+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Conversation:" android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView android:id="#+id/tvConvo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" />
</LinearLayout>
I tried running it, but nothing happens. When I click the button the TextView doesn't view the "Hello" message from the server.
You connect with your Android client to localhost.
Socket s = new Socket("localhost", 8080);
This would only work when your server is running on the Android device. But I think it is running on your PC. So, when you run your app on Android emulator, you can connect to 10.0.2.2 in order to contact the host. On a real device, you have to find out your servers IP address which can be reached by the Android device, e.g. via Wi-Fi.
If your server is on Windows, type cmd in the Start menu search box and then type ipconfig at the command prompt. You will see something like IVP4 Address----- 192.168.0.101. you need to use this address and port number on your client.
Related
I have an app which has to poll a TCP server (on LAN) to fetch some data, I'm doing this using sockets in an AsyncTask class.
It works well for the first few requests. But at a certain point, the app must poll the server every 2s (using a timer). This is when the AsyncTask stops executing and the TCP messages do not get sent to the server. I can't figure out why.
Code is below. Any help will be appreciated!
Thank you!
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class TcpTask extends AsyncTask<String, Void, String> {
Context context;
TcpResultListener tcpResultListener;
int actionCode;
String TAG = "TcpTask";
String SERVER_IP = "192.168.1.12", SERVER_PORT = "1234";
Socket socket = null;
PrintWriter out;
int readTimeout;
// Creating listener
public void setOnTcpResultsListener(TcpResultListener tcpResultListener, int actionCode) {
this.tcpResultListener = tcpResultListener;
this.actionCode = actionCode;
}
// Constructor with context as parameter
public TcpTask(Context context, int timeout) {
this.context = context;
this.readTimeout = timeout;
}
#Override
protected String doInBackground(String... params) {
String result = null;
try {
//Create a client socket and define internet address and the port of the server
socket = new Socket(params[0], Integer.parseInt(params[1]));
Log.d(Constants.TAG, "Socket created");
//Setting timeout for readLine
socket.setSoTimeout(readTimeout);
Log.d(Constants.TAG, "Timeout set");
//Get the output stream of the client socket
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(Constants.TAG, "PrinterWriter created");
//Write data to the output stream of the client socket
out.println(params[2]);
Log.d(Constants.TAG, "Sending TCP data: " + params[2]);
//Get the input stream of the client socket
InputStream is = socket.getInputStream();
//Buffer the data coming from the input stream
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//Read data in the input buffer
result = br.readLine();
} catch (NumberFormatException e) {
Log.d("TcpException", e.toString());
} catch (UnknownHostException e) {
Log.d("TcpException", e.toString());
} catch (IOException e) {
Log.d("TcpException", e.toString());
}
try {
Log.d(Constants.TAG, "Socket:: " + socket);
if(socket != null){
socket.close();
}
} catch (IOException e) {
Log.d(Constants.TAG, e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
Log.d(Constants.TAG, "String:: " + result);
tcpResultListener.onResultsReceived(result, actionCode);
}
}
The method I use to call the AsyncTask:
void sendTCP(String msg) {
TcpTask tcpTask = new TcpTask(this, 8000);
// Setting listener for tcpTask to send back result
tcpTask.setOnTcpResultsListener(AddSpaceActivity.this, 1);
// TODO: Change the data being passed below
//Pass the server ip, port and client message to the AsyncTask
tcpTask.execute(gwIP, gwPort, msg);
}
EDIT: Timer code:
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d(Constants.TAG, "Timer fired:: " + firstReceived);
if(firstReceived){
sendTCP(Constants.NETWORK_STATUS_REQUEST);
}
}
}, 3000, 2000);
I am trying to develop an app in which
1.client sends request to server for connection(IP address+PORT no.)+sends data using "PrintStream"+Tries to read the data from Server(Using Inputstream)
2.Client creates the socket.
3.Server reads the data send by Client
4.SERVER writes the data using "PrintStream" at same time point no 3.
Problem is at point 4 Data written by SERVER is not Read by "INPUTSTREAM" of client(Point 1)
I dont know these Simultaneous operation are possible or not.If possible then how.If not then what is the alternate way?
Server Code
package com.example.loneranger.ser;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
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.util.Enumeration;
public class MainActivity extends Activity {
TextView ip;
TextView msg;
String data = "";
ServerSocket httpServerSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
ip.setText(getIpAddress() + ":"
+ 8080 + "\n");
Server server = new Server();
server.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (httpServerSocket != null) {
try {
httpServerSocket.close();
} catch (IOException e) {
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 += "IP: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
private class Server extends Thread {
#Override
public void run() {
Socket socket = null;
try {
httpServerSocket = new ServerSocket(8888);
while(true){
socket = httpServerSocket.accept();
HttpResponseThread httpResponseThread =
new HttpResponseThread(
socket);
httpResponseThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class HttpResponseThread extends Thread {
Socket socket;
HttpResponseThread(Socket socket){
this.socket = socket;
}
#Override
public void run() {
BufferedReader BReader;
PrintWriter printer;
String request;
try { InputStream inputStream = socket.getInputStream();
BReader = new BufferedReader(new InputStreamReader(inputStream));
request = BReader.readLine();
Thread.sleep(500);
printer = new PrintWriter(socket.getOutputStream(), true);
printer.print("hello laundu");
printer.flush();
String ip123=socket.getInetAddress().toString();
printer.close();
BReader.close();
socket.close();
data += "Request of " + request
+ " from "+ ip123 + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(data);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
}
}
Client Code
mport android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
MainActivity activity;
OutputStream outputStream;
BufferedReader BReader;
String request;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse=textResponse;
this.activity=activity;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
Server server = new Server(socket);
server.start();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.print("futfujb");
out.flush();
/*
* notice: inputStream.read() will block if no data return
*/
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} /*finally {
if (socket != null) {
try {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
private class Server extends Thread {
Socket socket;
Server(Socket socket)
{
this.socket=socket;
}
#Override
public void run() {
try { //Thread.sleep(500);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
if(inputStream.available()>0)
{
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
inputStream.close();
socket.close();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As I commented above, there is nothing in this code that corresponds to either of these steps:
2.Server gets the request creates new SOCKET connection.
(a) There is no request, and (b) the server does not create a new connection. The client creates it. The server accepts it.
3.Server reads the data send by Client.
The client doesn't send any data.
There are two problems here (at least):
The server is blocking in readLine() waiting for a message that the client never sends. So it never gets to its own send, so nothing is received by the client. Have the client send a request, as per the comments.
The client is incorrectly using available(). Remove this test and let the client fall through into the read loop. It will exit that when the peer (the server) closes the connection.
I have written a small client server application for android. The client is a Java program running on my PC while my Android phone is a server. I'm facing force close issues in my server program. The server starts pretty good, but when I send a string from my PC client, the android application (server) force closes. It has become really annoying. Please help!
Here is my client program running on my PC:
package javaNetPackage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
public class javaClient {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String serverIpAddress = "10.81.242.220";
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
echoSocket = new Socket(serverAddr, 4444);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to server");
System.exit(1);
}
String str = JOptionPane.showInputDialog("Please give number");
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(echoSocket.getOutputStream())),true);
out.println(str);
out.close();
in.close();
echoSocket.close();
}
}
And here is my server code running on Android:
package com.vinit.androidserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MainActivity extends Activity {
ServerSocket ss = null;
String mClientMsg = "";
Thread myCommsThread = null;
protected static final int MSG_ID = 0x1337;
public static final int SERVERPORT = 4444;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("Nothing from client yet");
this.myCommsThread = new Thread(new CommsThread());
this.myCommsThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(mClientMsg);
break;
default:
break;
}
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT );
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
m.what = MSG_ID;
try {
if (s == null)
s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String st = null;
st = input.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Permissions:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Update:: Okay, I solved the issue of force close. I deleted the permission tags in manifest.xml and re-typed them. But now, I'm facing a different problem here. The sent string from PC client is not getting displayed in my server TextView (textView1 in layout xml, referred to as tv in server code). Default message in tv is "Nothing from client yet". When I send a string from PC client, default message disappears but sent string is not updated in server TextView (tv).
You should set the received string to your Message object sent in myUpdateHandler.sendMessage(m); instead of your mClientMsg field.
You can create and send the Message object as below:
String st = null;
st = input.readLine();
Message msg = Message.obtain(myUpdateHandler, MSG_ID, st);
msg.sendToTarget();
To get the value in your handler,
case MSG_ID:
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText((String) msg.obj);
break;
I would suggest you use a Bundle object instead of the raw object though. http://developer.android.com/reference/android/os/Message.html#setData(android.os.Bundle)
The reason you ends up with an empty string is because your handler and CommsThread run in different threads and thus not using the same instance of mClientMsg.
i.e. changes in CommsThread to mClientMsg is not visible in your handler.
I'm sort of new to Android application development. I already created a very simple application that turns the device's flashlight on/off.
I'd like to try and create a messaging application where you can chat with your friends when both of you are connected to a Wifi. Sort of like "WhatsApp", "Viber", etc..
I would be really happy if you could give me guidelines and help me get the idea of how to develop such an application.
Thank you so much,
Orel.
For that you need to create server program, that will authenticate username & password and communication between diff users.., etc, and you need to send the response based on the user query.
For any network communication application consists of two components:
Server
Client
In the case of WhatsApp android app,its a client application which communicate's with the WhatsApp server.
The server with exchange the data from one client to another client, the client may be desktop, android mobile, iPhone,...etc
Generally chat programs will implemented using sockets, and its depends upon the architecture and technologies which you will chose.
Using this:
ChatServerSide
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
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.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ChatServerSide extends Activity implements View.OnClickListener {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
TextView tvMyIp;
Socket socket;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_activity);
iniUi();
iniListener();
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
tvMyIp.setText("Waiting devices on " + getIpAddress());
}
private void iniUi() {
tvMyIp = (TextView) findViewById(R.id.tvMyIp);
btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
etInputMessage = (EditText) findViewById(R.id.etInputMesage);
tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}
private void iniListener() {
btnSendMsg.setOnClickListener(this);
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onClick(View view) {
try {
String str = etInputMessage.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: " + str + "\n");
etInputMessage.setText("");
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
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()) {
String read = null;
try {
read = input.readLine();
if (read == null) {
read = "Client has leave the chat";
socket.close();
updateConversationHandler.post(new updateUIThread(read));
break;
}
updateConversationHandler.post(new updateUIThread("Client Says: " + read));
}catch(IOException e){
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
tvOutputMessage.setText(tvOutputMessage.getText().toString() + msg + "\n");
}
}
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 += inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
ChatClientSide
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClientSide extends Activity implements View.OnClickListener {
private Handler handler = new Handler();
private Socket socket;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
Handler updateConversationHandler;
TextView tvMyIp;
private static final int SERVERPORT = 6000;
private static String SERVER_IP = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_activity);
iniUi();
iniListener();
SERVER_IP = ActivityMain.ipToConnect;
updateConversationHandler = new Handler();
receiveMsg();
}
#Override
protected void onStop() {
super.onStop();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getServerIp(Intent intent) {
Bundle bundle = intent.getExtras();
String ip = bundle.getString("destAdress");
tvMyIp.setText("Is connected to " + ip);
return ip;
}
private void iniUi() {
tvMyIp = (TextView) findViewById(R.id.tvMyIp);
btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
etInputMessage = (EditText) findViewById(R.id.etInputMesage);
tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}
private void iniListener() {
btnSendMsg.setOnClickListener(this);
}
#Override
public void onClick(View view) {
try {
String str = etInputMessage.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: " + str + "\n");
etInputMessage.setText("");
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void receiveMsg() {
new Thread(new Runnable() {
#Override
public void run() {
final String host = SERVER_IP;
BufferedReader in = null;
try {
socket = new Socket(host, SERVERPORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
String msg = null;
try {
msg = in.readLine();
//msgList.add(msg);
} catch (IOException e) {
e.printStackTrace();
}
if (msg == null) {
break;
} else {
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg) {
final String mssg = msg;
handler.post(new Runnable() {
#Override
public void run() {
tvOutputMessage.setText(tvOutputMessage.getText().toString() + "Server Says: " + mssg + "\n");
}
});
}
}
chat_main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvMyIp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnSendMsg"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="send"
android:layout_weight="0" />
<EditText
android:id="#+id/etInputMesage"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/tvOutputMessage"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</TextView>
</LinearLayout>
</LinearLayout>
I'm building a very small app to send data from the cellphone to a computer. I've read a couple of examples and got the server and client code working. But when i try to connect them, got a "network unreachable" error. Any idea what am i doing wrong??
This is the Server Code:
import java.net.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Server {
static BufferedReader in = null;
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("FrameDemo");
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
try {
if (in != null)
in.close();
if (serverSocket.isClosed())
{}
else
serverSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JLabel Label = new JLabel("");
Label.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(Label, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
Label.setText("Empezo");
serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.err.println(e.getMessage());
System.exit(1);
}
Integer puerto = serverSocket.getLocalPort();
Label.setText("<html>Puerto Abierto: " + puerto.toString() + "<br>IP Servidor: " + serverSocket.getInetAddress().toString() + "</html>");
clientSocket = null;
try {
clientSocket = serverSocket.accept();
Label.setText("Conection Accepted");
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
while ((in.readLine()) != null) {
System.out.println("Mensaje: " + in.readLine());
}
}
}
And the Cliente part
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class PruebaSocket extends Activity {
/** Called when the activity is first created. */
Socket Skt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Enviar =(Button)findViewById(R.id.OK);
Button Salir = (Button)findViewById(R.id.SALIR);
final TextView IP = (TextView)findViewById(R.id.IP);
Skt = new Socket();
Enviar.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try{
Skt = new Socket("192.168.1.101",4444);
CharSequence errorMessage = "Coneccted";
Toast.makeText(PruebaSocket.this, errorMessage, Toast.LENGTH_SHORT).show();
}
catch(Exception E)
{
CharSequence errorMessage = E.getMessage();
Toast.makeText(PruebaSocket.this, errorMessage, Toast.LENGTH_SHORT).show();
if (Skt.isConnected())
try {
Skt.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Salir.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
try {
Skt.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
}
}
192.168.1.101 it's the IP of the server.
I don't know much about java sockets but the normal usage of a socket is: create, bind, and put in listen mode (udp) or call .accept() (tcp). I can see Java also has the binding phase - http://download.oracle.com/javase/1.5.0/docs/api/java/net/ServerSocket.html#bind(java.net.SocketAddress, int).