Code :
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://192.168.1.8/android-im/index.php"; //TODO change to your WebAPI Address
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = "failed";
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false)
{
//appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
}
Related
I have developed sample Android app for Socket communication over WiFi, with multiple clients. I am using JsonWriter for writing messages and JsonReader for reading messages.
When communicating one-to-one is no issue, but one-to-many is having some issues.
For Example:
My server S1 is connected with Client C1,C2 and C3, when the server try to send messages to all client at a same time the client C3 only receiving the messages but not others.
ServerSocketClass
public class ServiceMain extends Service implements OnResponseJsonWriter {
private boolean isRunning = false;
private MyThread myThread;
static final int SocketServerPORT = 8080;
ServerSocket serverSocket;
static List<ChatClient> userList;
static String msgLog = "";
private String TAG = ServiceMain.class.getSimpleName();
private boolean isServerAction = false;
private String TOKEN_REQUEST;
private Context mContext;
private JsonWriter writer = null;
private JSON_Writer jsonWriter;
private DataInputStream dataInputStream = null;
private DataOutputStream dataOutputStream = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mContext = ServiceMain.this;
userList = new ArrayList<ChatClient>();
myThread = new MyThread();
}
#SuppressWarnings("deprecation")
#Override
public synchronized void onDestroy() {
try {
if (isRunning) {
myThread.interrupt();
myThread.stop();
}
} catch (UnsupportedOperationException e) {
}
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!isRunning) {
myThread.start();
isRunning = true;
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onJsonWriterRespnse(boolean isSuccess) {
try {
writer.flush();
dataOutputStream.flush();
} catch (Exception e) {
Log.e(TAG, "onJsonWriterRespnse " + e);
}
}
class MyThread extends Thread {
static final long DELAY = 3000;
#Override
public void run() {
while (isRunning) {
try {
ChatServerThread chatServerThread = new ChatServerThread();
chatServerThread.start();
Thread.sleep(DELAY);
} catch (InterruptedException e) {
isRunning = false;
}
}
}
}
private class ChatServerThread extends Thread {
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
while (true) {
socket = serverSocket.accept();
ChatClient client = new ChatClient();
userList.add(client);
ConnectThread connectThread = new ConnectThread(client, socket);
connectThread.start();
}
} catch (IOException e) {
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class ChatClient {
String id;
Socket socket;
ConnectThread chatThread;
#Override
public String toString() {
return socket.getInetAddress().getHostAddress();
}
}
private class ConnectThread extends Thread {
Socket socket;
ChatClient connectClient;
String msgToSend = "";
ConnectThread(ChatClient client, Socket socket) {
connectClient = client;
this.socket = socket;
client.socket = socket;
client.chatThread = this;
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
String n = dataInputStream.readUTF();
connectClient.id = n;
socketConnectionResponse(connectClient, connectClient.id);
while (true) {
if (dataInputStream.available() > 0) {
}
isServerAction = false;
if (!msgToSend.equals("")) {
TeacherAttention attentionModel;
switch (msgToSend) {
case Constants.LOOK_AT_ME:
isServerAction = true;
TOKEN_REQUEST = Constants.LOOK_AT_ME;
msgToSend = "";
attentionModel = new TeacherAttention(Constants.TEACHER_ATTENTION_REQUEST,
Constants.RESPONSE_SUCCESS, Constants.LOOK_AT_ME);
writer = new JsonWriter(new OutputStreamWriter(dataOutputStream, "UTF-8"));
writer.setIndent(" ");
// for write JSON
jsonWriter = new JSON_Writer(mContext, writer, attentionModel, "");
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e("TAG", "finally??");
userList.remove(connectClient);
}
}
private void sendMsg(String msg) {
msgToSend = msg;
}
}
public static void broadcastMsgToAll(String msg) {
for (int i = 0; i < userList.size(); i++) {
userList.get(i).chatThread.sendMsg(msg);
}
}
/**
* send response to single user
*
* #param client
* #param userid
*/
public void socketConnectionResponse(ChatClient client, String userid) {
if (client != null) {
client.chatThread.sendMsg(userid);
} else {
Toast.makeText(ServiceMain.this, "No user connected", Toast.LENGTH_LONG).show();
}
}
}
ClientSocketClass:
public class ClientSocketService extends Service implements OnResponseJsonWriter,
OnResponseJsonReader {
private static String TAG = ClientSocketService.class.getSimpleName();
static final int socketServerPORT = 8080;
private ChatClientThread chatClientThread = null;
static String msgToSend = "";
static boolean goOut = false, isSocketRunning = false;
private JsonReader reader;
private Context mContext;
private DataOutputStream dataOutputStream = null;
private DataInputStream dataInputStream = null;
private JsonWriter writer = null;
private JSON_Reader jsonReader;
private JSON_Writer jsonWriter;
public static Socket socket = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
db = new DatabaseHelper(this);
getAllStudent = new ArrayList<>();
mContext = ClientSocketService.this;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
chatClientThread = new ChatClientThread(getUserID(), getTeacherIP(), socketServerPORT);
chatClientThread.start();
return super.onStartCommand(intent, flags, startId);
}
private class ChatClientThread extends Thread {
String name;
String dstAddress;
int dstPort;
ChatClientThread(String name, String address, int port) {
this.name = name;
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(name);
dataOutputStream.flush();
while (!goOut) {
if (dataInputStream.available() > 0) {
reader = new JsonReader(new InputStreamReader(dataInputStream, "UTF-8"));
try {
jsonReader = new JSON_Reader(mContext, reader);
} catch (Exception e) {
Log.e(TAG, "dataInputStream" + e);
} finally {
}
}
}
isSocketRunning = true;
}
} catch (UnknownHostException e) {
final String eString = e.toString();
Log.e("eString 1", "eString " + eString);
isSocketRunning = false;
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
Log.e("eString 2", "eString " + eString);
isSocketRunning = false;
} finally {
if (socket != null) {
try {
isSocketRunning = false;
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void sendMsg(String msg) {
msgToSend = msg;
}
private void disconnect() {
goOut = true;
}
public static boolean isSocketRunning() {
return isSocketRunning;
}
#Override
public void onJsonWriterRespnse(boolean isSuccess) {
try {
writer.flush();
dataOutputStream.flush();
} catch (IOException e) {
Log.e(TAG, "onJsonWriterRespnse " + e);
isSocketRunning = false;
}
}
#Override
public void onSocketReaderResponse(String requestToken, final ArrayList<SocketResponseModel> socketResponse) {
}
#Override
public void onSocketResponseUpdateIP(SocketResponseUpdateIp responsIp) {
}
#Override
public void onTeacherAttention(TeacherAttention teacherAttention) {
Intent lookIntent;
switch (teacherAttention.getTokenStatus()) {
case Constants.LOOK_AT_ME:
lookIntent = new Intent(this, LookAtMeActivity.class);
lookIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(lookIntent);
break;
}
}
Server: PC
Client: Android
So my Client/Server app consists in opening webpages and executing a bot, everything is fine if I use only for a router, but I would like to be able to to connect in different places (different router/PC).
I was searching for "Wi-fi Search of IP" and got nothing.
Is it possible to give to the Server side a fix IP? like always 192.168.1.68?
Client Code
public class AndroidClient extends Activity
{
EditText episode;
Spinner spinner1;
String result;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
episode = (EditText) findViewById(R.id.episode);
buttonConnect = (Button) findViewById(R.id.connect);
buttonClear = (Button) findViewById(R.id.clear);
spinner1 = (Spinner) findViewById(R.id.Animes);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Anime, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
addListenerOnSpinnerItemSelection();
addListenerOnButton();
}
public void addListenerOnSpinnerItemSelection() {
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.Animes);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MyClientTask myClientTask = new MyClientTask();
myClientTask.execute();
}
});
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("10.1.3.68", 8080);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(episode.getText() + "-" + String.valueOf(spinner1.getSelectedItem()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Server Code
public class ServerSide extends Application
{
TextField textTitle;
Label labelSys, labelPort, labelIp;
Label labelMsg;
CheckBox optWelcome;
ServerSocket serverSocket;
String message = "";
String result;
#Override
public void start(Stage primaryStage) {
textTitle = new TextField();
labelSys = new Label();
labelPort = new Label();
labelIp = new Label();
labelMsg = new Label();
labelIp.setText(getIpAddress());
VBox mainLayout = new VBox();
mainLayout.setPadding(new Insets(5, 5, 5, 5));
mainLayout.setSpacing(5);
mainLayout.getChildren().addAll(textTitle,
labelSys, labelPort, labelIp,
labelMsg);
StackPane root = new StackPane();
root.getChildren().add(mainLayout);
Scene scene = new Scene(root, 300, 400);
primaryStage.setTitle("One Piece");
primaryStage.setScene(scene);
primaryStage.show();
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.setDaemon(true);
socketServerThread.start();
}
public static void main(String[] args) {
launch(args);
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
Socket socket = null;
serverSocket = new ServerSocket(SocketServerPORT);
Platform.runLater(new Runnable() {
#Override
public void run() {
labelPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
count++;
//Start another thread
//to prevent blocked by empty dataInputStream
Thread acceptedThread = new Thread(
new ServerSocketAcceptedThread(socket, count));
acceptedThread.setDaemon(true); //terminate the thread when program end
acceptedThread.start();
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private class ServerSocketAcceptedThread extends Thread {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
int count;
ServerSocketAcceptedThread(Socket s, int c) {
socket = s;
count = c;
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
//If dataInputStream empty,
//this thread will be blocked by readUTF(),
//but not the others
String messageFromClient = dataInputStream.readUTF();
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n"
+ "Msg from client: " + messageFromClient + "\n";
Platform.runLater(new Runnable() {
#Override
public void run() {
labelMsg.setText(message);
}
});
String string = messageFromClient;
String[] parts = string.split("-");
String episode = parts[0];
String anime = parts[1];
String OneP = new String("One Piece");
String Naruto = new String ("Naruto");
String Bleach = new String ("Bleach");
int EPnumb = Integer.parseInt(episode);
if (EPnumb < 10) {
result = "00" + episode;
}
else if (EPnumb < 100 && EPnumb >= 10) {
result = "0" + episode;
}
else { result = episode; }
if (anime.equals(OneP)){
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/One-Piece/Episode-"+ result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}}
else {
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/Naruto-Shippuuden/Episode-"+result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
private java.lang.String parseInt(java.lang.String episode) {
// TODO Auto-generated method stub
return null;
}
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 ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
return ip;
}
public DataInputStream String(String string) {
return null;
}
}
You can use ServerSocket(int port, int backlog, InetAddress bindAddr)
Constructs a new ServerSocket instance bound to the given localAddress and port.
I am developing andorid aplication for connection to ELM327 for car unit trought Wifi (my adapter: http://www.obdinnovations.com/mini-vgate-elm327-wifi-obd2-auto-diagnostics-scanner).
How should I connect to this OBD2 adapter and then send some signals?
OutputStream outStream = null;
InputStream inStream = null;
Socket socket = null;
InetAddress serverAddr = null;
String serverProtocol = "http";
String serverIpAddress = "192.168.0.10";
public static final int SERVERPORT = 35000;
try {
serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, SERVERPORT);
socket.setKeepAlive(true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sendDataToOBD(socket1, "ATZ\r");
Log.e("OBD: ATZ", readDataFromOBD(socket));
public void sendDataToOBD(Socket socket1, String paramString) {
try {
outStream = socket1.getOutputStream();
byte[] arrayOfBytes = paramString.getBytes();
outStream.write(arrayOfBytes);
} catch (Exception localIOException1) {
localIOException1.printStackTrace();
}
}
public String readDataFromOBD(Socket socket1) {
while (true) {
try {
inStream = socket1.getInputStream();
String str1 = "";
char c = (char) inStream.read();
str1 = str1 + c;
if (c == '>') {
String datafromOBD = str1.substring(0, -2 + str1.length()).replaceAll(" ", "").trim();
return datafromOBD;
}
} catch (IOException localIOException) {
return localIOException.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I try also with:
URL url = null;
try {
url = new URL(serverProtocol, serverIpAddress, SERVERPORT, "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
And methods param was HttpURLConnection connection instead of Socket socket1.
But I can't receive any signal. What's wrong with my code? Any suggestions?
I am working on an android project. Where I am using Socket programming.
But I am getting
java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused.
from emulator.
I have changed the localhost to
"10.0.2.2" ("http://10.0.2.2/abc.php").
I have also followed the java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused.
But I did not get any solution.
Also please note emulator ip address doesn't match with localhost ip address.So I don't know how to get around this.
Here is the code requested for:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import android.util.Log;
import com.mekya.interfaces.IAppManager;
import com.mekya.interfaces.ISocketOperator;
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://billbahadur.com/demo/androidchat/android_im/";
private int listeningPort = 5550;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false)
{
appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public boolean sendMessage(String message, String ip, int port)
{
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
} catch (UnknownHostException e) {
return false;
//e.printStackTrace();
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
}
change android_im to android-im because that is what your folder name would be kept in the web server directory of your server. Also mention the port number of the server in the authentication address.
hi i am trying to send a file through sockets in an android messenger. for some reason its not working. at times it does output a file but transfers no bytes that is the output file is of 0 bytes and sometimes the output or the received file is of 57 bytes precisely. following the code where i actually send the file :
public boolean sendFile(String ip, int port) {
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File("/sdcard/chats/gas.jpg/");
filesize = (int) f.length();
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
this is where i send the inputstream to the receivefile method :
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
//PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
InputStream is=clientSocket.getInputStream();
if (inputLine.contains("Text") == true) {
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");
} else if (inputLine.contains("Text") == false) {
Log.i("SocketOP","filee");
appManager.fileReceived(is);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
}
}
}
and finally this is how i receive the file :
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
//int filesize=6022386; // filesize temporary hardcoded
int bytesRead;
final byte[] aByte = new byte[is.toString().length()];
if (is!= null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/gas1.jpg/");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
}}
the following is the complete socketoperator file :
package hardy.scl.communication;
import hardy.scl.interfaces.IAppManager;
import hardy.scl.interfaces.ISocketOperator;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import android.util.Log;
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://10.10.10.100/chippers/";
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
public int filesize ;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
Socket fileSocket=null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
this.fileSocket=socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
InputStream is=fileSocket.getInputStream();
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("Text") == true)
{
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");}
else if
(inputLine.contains("Text") == false)
{
Log.i("SocketOP","filee");
appManager.fileReceived(is);
}
else{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
fileSocket.shutdownInput();
fileSocket.shutdownOutput();
fileSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
SocketOperator.this.sockets.remove(fileSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public boolean sendMessage(String message, String ip, int port)
{
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
//OutputStreamWriter outputStream = new OutputStreamWriter(socket.getOutputStream());
//outputStream.write("Text");
// outputStream.flush();
String flag = "Text";
message = message+flag;
out.println(message);
} catch (UnknownHostException e) {
return false;
//e.printStackTrace();
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
#Override
public boolean sendFile(String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File("/sdcard/chats/gas.jpg/");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
int readData;
byte[] buffer = new byte[1024];
bis.read(buffer, 0,buffer.length);
OutputStream os = socket.getOutputStream();
while((readData=bis.read(buffer))!=-1){
os.write(buffer,0,readData);
Log.i("SocketOP", "sendFILE-3");
}
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
}
This is my IMService service that runs and calls startlistening. i am totally cluless. its giving me an error as suspected. how do i go about resolving this now..
IMService code block :
public void onCreate()
{
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
// showNotification();
conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
timer = new Timer();
Thread thread = new Thread()
{
#Override
public void run() {
//socketOperator.startListening(LISTENING_PORT_NO);
Random random = new Random();
int tryCount = 0;
while (socketOperator.startListening(10000 + random.nextInt(20000)) == 0 )
{
tryCount++;
if (tryCount > 10)
{
// if it can't listen a port after trying 10 times, give up...
break;
}
}
}
};
thread.start();
}
Try this for fileReceived
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/gas1.jpg/");
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(aByte)) != -1) {
bos.write(aByte, 0, bytesRead);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
}}
EDIT
You can use 2 sockets, listening on different ports. E.g.
MESSAGE_PORT = 20000
FILE_PORT = 20001
And you run 2 ReceiveConnections, e.g. ReceiveFileConnection and ReceiveMessageConnection. I don't know where do you start port listening, it's not in your code above.
In client you'll also need to split sending to 2 part, message sender sends to MESSAGE_PORT and file sends files to FILE_PORT.
EDIT2
http://pastebin.com/MfMuSF2Q
I split ReceiveConnection into 2 classes ReceiveMessageConnection and ReceiveFileConnection.
I modified method startListening, so it takes parameter which listener we want to start message or file. So you need to call it twice like
startListening(MESSAGE_PORT, true);
startListening(FILE_PORT, false);
But call them in different threads.
To send message you call sendMessage("Message", ip, MESSAGE_PORT) and for files sendFile(ip, FILE_PORT).
Hope this will help.