I am trying to do a simple chat client for the Android (running 2.3.3 on an emulator on my computer and programing in eclipse. Below is a copy of my client code which is working fine as a normal java app. Below that I have what I have been working on for the Android client-- I am just stuck on how to make the client work for the phone and how to add certain listeners. Below that is a copy of my layout.


Normal Chat Client

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;

public class ChatClient extends JFrame {
    Socket      _socket;
    JTextArea   _textArea;
    JTextField  _textField;
    JScrollPane _scrollPane;

    public ChatClient() {
        super("Chat Client");

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent ev) {
                try {
                    InetAddress host = InetAddress.getLocalHost();
                    sendText(host.getHostAddress() + " Left.");

                    _socket.close();
                }
                catch (IOException ex) {
                    System.err.println("Close failed. " + ex);
                }
                System.exit(0);
            }
        });

        setLayout(new BorderLayout());

        _textArea = new JTextArea(10, 40);
        _textArea.setLineWrap(true);
        _textArea.setEditable(false);

        _scrollPane = new JScrollPane(_textArea);
        add(_scrollPane, BorderLayout.CENTER);

        _textField = new JTextField(30);
        _textField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
                sendText(_textField.getText());

                _textField.setText("");
            }
        });

        JButton sendButton = new JButton("Send");
        sendButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ev) {
                sendText(_textField.getText());

                _textField.setText("");
            }
        });

        JPanel entryPanel = new JPanel(new BorderLayout());
        entryPanel.add(_textField, BorderLayout.CENTER);
        entryPanel.add(sendButton, BorderLayout.EAST);
        add(entryPanel, BorderLayout.SOUTH);

        pack();
        setVisible(true);

        try {
            InetAddress host    = InetAddress.getLocalHost();
            String      address = host.getHostAddress();
            _textArea.append("Connecting to: " + address + "\n");
            _socket = new Socket(host, 7777);
            _textArea.append("Connected\n");

            sendText(address + " Joined.");

            while (!_socket.isClosed()) {
                try {
                    InputStream input     = _socket.getInputStream();
                    int         available = input.available();
                    if (available > 0) {
                        byte[] bytes = new byte[available];
                        input.read(bytes);

                        _textArea.append(new String(bytes) + "\n");

                        JScrollBar scroll = _scrollPane.getVerticalScrollBar();
                        scroll.setValue(scroll.getMaximum());
                    }

                    Thread.sleep(100);
                }
                catch (IOException ex) {
                    System.err.println("Listen failed " + ex);
                }
                catch (InterruptedException ex) {
                    System.err.println("Sleep interrupted " + ex);
                }
            }
        }
        catch (IOException ex) {
            System.err.println("Connection failed. " + ex);
            System.exit(1);
        }
    }

    private void sendText(String s) {
        try {
            OutputStream output = _socket.getOutputStream();
            output.write(new String(s).getBytes());
            output.flush();
        }
        catch (IOException ex) {
            System.err.println("Send error: " + ex);
        }
    }

    public static void main(String[] args) {
        new ChatClient();
    }
}

Unworking Android Client

package android.test;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import java.io.*;
import java.net.*;

public class Main extends Activity {
	private Socket                        _socket;
	private EditText                      _editText;
	private EditText					  _textArea;
	private Button                        _button;
	private AsyncTask<Void, String, Void> _task;
	private int                           _appendCount;
	private boolean                       _running;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        _editText = (EditText)findViewById(R.id.editText);
        _textArea = (EditText)findViewById(R.id.editText1);
        _button   = (Button)findViewById(R.id.button);
        
        Log.d("onCreate()", "Hello World");
        
        try {
        	_socket = new Socket(InetAddress.getByName("10.0.2.2"), 7777);
        }
        catch (IOException ex) { Log.e("Socket connection error", ex.toString()); }
        
        _task = new AsyncTask<Void, String, Void>() {
            @Override
            protected Void doInBackground(Void... param) {
            	while (true) {
            		try {
                        InputStream input     = _socket.getInputStream();
                        int         available = input.available();
                        if (available > 0) {
                            byte[] bytes = new byte[available];
                            input.read(bytes);

                            _editText.append(new String(bytes) + "\n");
                        }
            	
            			Thread.sleep(10);
            		}
            		catch (InterruptedException ex) { Log.e("interrupted", ex.toString()); }
            		catch (IOException ex) { System.err.println("Listen failed " + ex); }
            	}
            }

            @Override
            protected void onProgressUpdate(String... progress) {
    			_editText.append(progress[0]);
            }
        };        
    }
    
    public void buttonClicked(View view) {
    	sendText(_textArea.getText());

        _textArea.setText("");
    }
    
    private void sendText(String s) {
        try {
            OutputStream output = _socket.getOutputStream();
            output.write(new String(s).getBytes());
            output.flush();
        }
        catch (IOException ex) {
            System.err.println("Send error: " + ex);
        }
    }

}

Layout

<?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" >

    <EditText
        android:id="@+id/editText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:editable="false"
        android:lines="4" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="buttonClicked"
            android:text="Send" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Exit" />
    </LinearLayout>

</LinearLayout>

have you given permission to your android app to access the internet??

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.