Simple Android Socket Programming - android

I am learning android socket programming. The code is given below. At the first click of the button, message is being sent to the server successfully but after the second click message is not going to the server and also it is not showing any error.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private InetAddress address;
private Button send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button) this.findViewById(R.id.Send);
send.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new Sender().execute("xxx.xxx.xx.xxx");
}
private class Sender extends AsyncTask<String, Void, Void> {
private Socket socket;
private Connector connector;
public Sender() {}
#Override
protected Void doInBackground(String... params) {
try {
address = InetAddress.getByName(params[0]);
socket = new Socket(address, 10001);
connector = new Connector(socket);
connector.write("Hello server, this is client");
} catch (UnknownHostException e) {
Log.d("Error", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("Error", e.getLocalizedMessage());
}
return null;
}
}
}
public class Connector {
private Socket socket;
private PrintWriter writer;
public Connector(Socket soc) {
socket = soc;
try {
writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
Log.d("Error", e.getLocalizedMessage());
}
}
public void write(String message) {
writer.println(message);
}
}

Related

How getOutputStream() of Socket from another class?

I have two classes:
MainActivity.class
ScreenCapture.class
and want getOutputStream(); from a Socket that is located on MainActivity.class.
Then i do:
MainActivity.INSTANCE.clientSocket.getOutputStream();
but is failing in this line ^, i not left logcat here because my logcat not is catching all events correctly, but from this description hope that someone can help.
MainActivity
public class MainActivity extends AppCompatActivity {
public static final MainActivity INSTANCE = new MainActivity();
public Socket clientSocket;
private final int SERVERPORT = 101;
private final String SERVER_IP = "192.168.15.13";
/////////////////////////////////////////////// CLIENTSOCKET //////////////////////////////////////////////////////
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
clientSocket = new Socket(serverAddr, SERVERPORT);
new Thread(new CommsThread()).start();
} catch (Exception e1) {
System.out.println(e1.toString());
}
}
}
class CommsThread implements Runnable {
#Override
public void run() {
try {
System.out.println("Waiting for server request");
while(clientSocket.isConnected()){
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true);
if (reader.ready()) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
if(line != null && !line.trim().isEmpty()) {
if(line.equalsIgnoreCase("screen")){
// Do something
out.flush();
}
if(line.equalsIgnoreCase("exit")) break;
}
}
}
Thread.sleep(100);
}
System.out.println("Shutting down Socket!!");
clientSocket.close();
} catch (Exception e1) {
System.out.println(e1.toString());
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
ScreenCapture
public class ScreenCaptureClass {
#UiThread
public boolean takeScreenshot(#NonNull Context context) {
//...
imageReader.setOnImageAvailableListener(new OnImageAvailableListener() {
#Override
public void onImageAvailable(final ImageReader reader) {
new AsyncTask<Void, Void, Bitmap>() {
#Override
protected Bitmap doInBackground(final Void... params) {
// ...
OutputStream outs = MainActivity.INSTANCE.clientSocket.getOutputStream(); // <= Error is here
}
}
}
}
}
}
Try to pass the socket's reference to your ScreenCaptureClass, you can try the following things:
You can pass your socket through the ScreenCaptureClass constructor (probably the best way).
Inside your ScreenCaptureClass you can add a static variable like private static OutputStream outputStream and a setter called from your MainActivity :
public static void setOutputStream(OutputStream os) {
outputStream = os;
}

Utilizing a socket in an android application

I've recently made a simple multicast client - server chat for java, now i am attempting to port the client on android.
The issue i'm facing is about dealing with the socket: the socket is created in a thread (as it'd crash the app otherwise), then i use the socket to istantiate an InputStreamReader and an OutputStreamWriter, however when trying to access any object created this way through a button listener, i'll get a null exception.
Also, if i were to put the two readers outside the thread, they would generate a null exception as well, even if i make sure the socket has been created already inside the thread.
I'd be glad if anybody could help me find out where is the issue, i apology for the messy code
public class ClientActivity extends AppCompatActivity {
public static int PORT = 1050;
public static String ADDRESS = "";
public static String USERNAME = "";
SusListenerThread inT;
public int ID;
public int roomID;
Socket socket = null;
BufferedReader in = null, stdIn = null;
PrintWriter out = null;
InputStreamReader isr;
OutputStreamWriter osw;
String userInput="";
public int mode=1;
public Button Bsend;
public Button Bbroadcast;
public Button Broom;
public EditText editMessage;
public EditText editReplies;
public EditText editRoom;
public TextView txtID;
public TextView txtUsername;
public TextView txtRoom;
public connectSocket coSocket;
public ClientActivity() {
}
public void setStuff(String str, int IDh){
this.ID=IDh;
this.USERNAME=str;
txtID.setText("ID: "+IDh);
txtUsername.setText("Username: "+str);
}
private class SusListenerThread extends Thread{
BufferedReader in = null;
public int ID;
public String username;
public boolean isSet=false;
//public View viiv;
public EditText editReplies;
public TextView txtRoom;
public SusListenerThread(InputStreamReader isr){
//this.viiv=viiv;
//editReplies = (EditText)viiv.findViewById(R.id.editReplies);
//txtRoom = (TextView)viiv.findViewById(R.id.textRoom);
in = new BufferedReader(isr);
//ClientGUI.jTextArea1.append(joj+"\n");
start();
}
#Override
public void run(){
String input="";
getStuff();
while(true)
{
try {
input=in.readLine();
} catch (IOException ex) {
//Logger.getLogger(ListenerThread.class.getName()).log(Level.SEVERE, null, ex);
}
if(input.charAt(0)=='0')
//ClientGUI.jTextArea1.append(input.substring(1)+"\n");
editReplies.append(input.substring(1)+"\n");
else if(input.charAt(0)=='1'){
//ClientGUI.jLabel2.setText("Stanza:"+input.substring(1));
txtRoom.setText("Room: "+input.substring(1));
}
}
}
public void getStuff(){
try {
ID=Integer.parseInt(in.readLine());
username+=in.readLine();
} catch (IOException ex) {
}
isSet=true;
}
}
private class connectSocket extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
}
#Override
protected Void doInBackground(Void... params) {
try {
socket= new Socket(ADDRESS,PORT);
} catch (IOException e) {
try {
socket = new Socket("127.0.0.1", 1050);
}catch(Exception ex){
e.printStackTrace();
};
}
/*
try{
isr = new InputStreamReader ( socket.getInputStream());
//in = new BufferedReader(isr);
inT=new SusListenerThread(isr);
osw = new OutputStreamWriter ( socket.getOutputStream());
BufferedWriter bw = new BufferedWriter( osw );
out = new PrintWriter (bw, true);
} catch (IOException ex) {}
*/
return null;
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
private class lilThread extends Thread {
public lilThread(){
start();
}
#Override
public void run(){
try {
socket = new Socket(ADDRESS, PORT);
}catch(Exception e ){
try {
socket = new Socket("79.42.49.56", 1050);
} catch (IOException ex) {ex.printStackTrace();}
}
try {
isr = new InputStreamReader ( socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
inT=new SusListenerThread(isr);
try {
osw = new OutputStreamWriter ( socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter( osw );
out = new PrintWriter (bw, true);
while(!inT.isSet){
try {
wait(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
setStuff(inT.username.substring(4)/*Mi ritornava nullUtente invece di Utente*/, inT.ID);
try {
wait(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
join();
} catch (InterruptedException e) {
e.printStackTrace();
}
interrupt();
}
}
public void InitializeStuff(){
lilThread lil = new lilThread();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_activity_gui);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Bsend = (Button)findViewById(R.id.buttonSenderino);
Bbroadcast = (Button)findViewById(R.id.buttonBroadcast);
Broom = (Button)findViewById(R.id.buttonRoom);
editMessage = (EditText)findViewById(R.id.editMessage);
editReplies = (EditText)findViewById(R.id.editReplies);
editRoom = (EditText)findViewById(R.id.editRoom);
txtID = (TextView)findViewById(R.id.textID);
txtUsername = (TextView)findViewById(R.id.textUsername);
txtRoom = (TextView)findViewById(R.id.textRoom);
this.PORT = getIntent().getExtras().getInt("PORT");
this.ADDRESS = getIntent().getExtras().getString("ADDRESS");
this.USERNAME = getIntent().getExtras().getString("USERNAME");
InitializeStuff();
Bsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//userInput= (EditText)v.findViewById(R.id.editMessage).getco;
userInput = editMessage.getText().toString();
if (!"".equals(userInput)) {
out.println(3 + userInput);
editMessage.setText("");
}
}
});
Bbroadcast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mode=0;
txtRoom.setText("Room: Broadcast");
roomID=-1;
out.println(mode);
editMessage.setText("");
}
});
Broom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mode=2;
try{
roomID=Integer.parseInt(editRoom.getText().toString());
txtRoom.setText("Stanza: "+roomID);
out.println(mode+""+roomID);
editRoom.setText("");
}catch(Exception e){
txtRoom.setText(" Err ");
}
}
});
}
}

Trying To Create a PC to Emulator Chat Application, getting an outputstream close null pointer exception

This is the code:
private EditText userText;
private Button bsend;
private TextView chatwindow;
private Socket connection;
private ObjectOutputStream output;
private ObjectInputStream input;
private String serverIP="10.0.2.2";
private String message="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userText = (EditText) findViewById(R.id.userText);
userText.setEnabled(false);
chatwindow=(TextView) findViewById(R.id.chatwindow);
bsend = (Button) findViewById(R.id.bsend);
startRunning();
bsend.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage(userText.getText().toString());
userText.setText("");
}
}
);
}
public void startRunning(){
try{
connectToServer();
setupStreams();
chatUp();
}
catch(EOFException e){
showMessage("\nServer Closed The Connection\n");
} catch (IOException e) {
e.printStackTrace();
}finally {
closeSystems();
}
}
public void connectToServer()throws IOException{
showMessage("\n********Connecting to Server......*********\n");
connection = new Socket(InetAddress.getByName(serverIP),5000);
showMessage("\n********Connection Successful*********\n");
}
public void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n***********Streams Setup Successfully***************\n");
}
public void chatUp() throws IOException{
ableToType(true);
showMessage("\nChatting can now Begin......\n");
do{
try {
message = (String) input.readObject();
sendMessage("\n"+message);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
while(!message.equals("SERVER - END"));
}
public void closeSystems() {
ableToType(false);
try{
output.close();
input.close();
connection.close();
}
catch(IOException e){
e.printStackTrace();
}
}
public void sendMessage(final String m){
try{
output.writeObject(m);
output.flush();
}
catch(IOException e){
e.printStackTrace();
}
}
public void showMessage(final String m){
chatwindow.append(m);
}
public void ableToType(final boolean tof){
userText.setEnabled(tof);
}
Trying to connect the emulator to the machine using the ip 10.0.2.2.
This happens only on the android system. I tested similar code on swing in eclipse and had no issue.
Appreciate it, if someone could tell me why I'm getting the Null pointer exception at output.close()
Thanks

Android background service to connect TCP server and handle message

According to an google example, i write an android client for a connection protocol based on TCP Socket server can send and receive information and it works good. But now I want it to become a background service for these transactions, after I left the application it also can notify me the message in time, I think a couple of days, but without success, someone can give me some help? Very grateful!
MainActivity
public class MainActivity extends Activity implements
Handler.Callback, ChatFragment.MessageTarget {
public static final String TAG = "rolingbaby";
public static final int MESSAGE_READ = 0x400 + 1;
public static final int MESSAGE_SEND = 0x400 + 2;
public static final String SERVER_URL = "192.168.191.2";
public static final int SERVER_PORT = 7838;
private Handler handler = new Handler(this);
private ChatFragment chatFragment;
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
InetAddress address = InetAddress.getByName(SERVER_URL);
Log.d(TAG, "Connected success!");
new MyTask1(((ChatFragment.MessageTarget) this).getHandler(),
address).execute();
} catch (UnknownHostException e) {
e.printStackTrace();
}
chatFragment = new ChatFragment();
getFragmentManager().beginTransaction()
.add(R.id.container, chatFragment, "trans")
.commit();
}
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d(TAG, readMessage);
(chatFragment).pushMessage("Rec: " + readMessage);
break;
case MESSAGE_SEND:
Object obj = msg.obj;
(chatFragment).setChatManager((ChatManager) obj);
}
return true;
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
Pivotal code in ChatFragment
public interface MessageTarget {
public Handler getHandler();
}
public void setChatManager(ChatManager obj) {
chatManager = obj;
}
public void pushMessage(String readMessage) {
adapter.add(readMessage);
adapter.notifyDataSetChanged();
}
MyTask
public class MyTask extends AsyncTask<Void, Void, Void>{
private static final String TAG = "ClientSocketHandler";
private Handler handler;
private ChatManager chat;
private InetAddress mAddress;
private static final int timeOut = 5000;
public MyTask(Handler handler, InetAddress serverAddress) {
this.handler = handler;
this.mAddress = serverAddress;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
Socket socket = new Socket();
try {
socket.bind(null);
socket.connect(new InetSocketAddress(mAddress.getHostAddress(),
MainActivity.SERVER_PORT), timeOut);
Log.d(TAG, "Launching the I/O handler");
chat = new ChatManager(socket, handler);
new Thread(chat).start();
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return null;
}
public ChatManager getChat() {
return chat;
}
}
ChatManager
public class ChatManager implements Runnable {
private Socket socket = null;
private Handler handler;
public ChatManager(Socket socket, Handler handler) {
this.socket = socket;
this.handler = handler;
}
private InputStream iStream;
private OutputStream oStream;
private static final String TAG = "ChatHandler";
public static String readMessage;
#Override
public void run() {
try {
iStream = socket.getInputStream();
oStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int bytes;
handler.obtainMessage(MainActivity.MESSAGE_SEND, this)
.sendToTarget();
while (true) {
try {
// Read from the InputStream
bytes = iStream.read(buffer);
if (bytes == -1) {
break;
}else{
readMessage = new String(buffer, "UTF-8");
}
// Send the obtained bytes to the UI Activity
Log.d(TAG, "Rec:" + String.valueOf(buffer));
handler.obtainMessage(MainActivity.MESSAGE_READ,
bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] buffer) {
try {
oStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
}

How to get connection with ServerSocket?

I want to develop app that connect to a server and send and receive message. i'm really beginner in that.
So,i wrote this code by This tutorial, and it seem that i get some mistake with the port or ip address beacuse i didn't get the message to the console. My inspiration is the problem is in my router setting maybe
Here is my android code (Project android)
public class MainActivity extends Activity {
Socket client;
PrintWriter printWriter;
EditText edIp,edPort,edMess;
String message;
int port = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edIp = (EditText) findViewById(R.id.edIp);
edPort = (EditText) findViewById(R.id.edPort);
edMess= (EditText) findViewById(R.id.edMessage);
edIp.setText("10.0.2.2");
edPort.setText("4444");
}
public void onClick(View v){
message = edMess.getText().toString();
edMess.setText("");
port = Integer.parseInt(edPort.getText().toString());
new Thread(new Runnable() {
#Override
public void run() {
try {
client = new Socket(edIp.getText().toString(),port);
printWriter = new PrintWriter(client.getOutputStream());
printWriter.write(message);
printWriter.flush();
printWriter.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}).start();
}
}
(java aplication)
public class Main {
public static void main(String[] args) throws IOException {
Socket clientSocket = null;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
System.out.println("Server started...");
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("error" + e);
}
Scanner in1 = new Scanner(clientSocket.getInputStream());
String mess;
while (true) {
if(in1.hasNext()){
mess = in1.nextLine();
System.out.println("Client message : "+mess);
}
}
}
}

Categories

Resources