天天看点

【聊天室】android 简单的聊天室

练习android网络知识。先介绍一下大概流程。首先是建立一个java工程,并创建两个java类,一个用于接收到客户端的连接,并把连接添加list中,第二类实现线程runnable接口,专门用来接收发送客户发送的信息。其次,建立android工程,并创建两个类,一个用于显示聊天界面,另一个负责接收服务器端返回的信息。这个例子肯定会有考虑不周的地方但是只是为了学习android中网络相关api的使用,所以请大家谨慎拍砖。

首先还是android的内容

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    xmlns:tools="http://schemas.android.com/tools" 

    android:layout_width="match_parent" 

    android:layout_height="match_parent" > 

    <EditText 

        android:id="@+id/et_show" 

        android:layout_width="fill_parent" 

        android:layout_height="wrap_content" 

        android:lines="5" 

        android:hint="所有聊天信息" 

        android:gravity="center" 

         /> 

    <EditText 

        android:id="@+id/et_input" 

        android:layout_below="@+id/et_show" 

        android:layout_width="fill_parent" 

        android:layout_height="wrap_content" 

        android:hint="输入聊天信息" 

        android:gravity="center" 

         /> 

    <Button  

        android:id="@+id/bt_send" 

        android:layout_below="@+id/et_input" 

        android:layout_width="fill_parent" 

        android:layout_height="wrap_content" 

        android:text="发送信息" 

        /> 

< /RelativeLayout> 

接着是MainAvitvity.java

[java] 

public class MainActivity extends Activity { 

    private EditText et_show,et_input; 

    private Button bt_send; 

    private OutputStream os; 

    private Handler handler; 

    @Override 

    protected void onCreate(Bundle savedInstanceState) { 

        super.onCreate(savedInstanceState); 

        setContentView(R.layout.activity_main); 

        et_input = (EditText) this.findViewById(R.id.et_input); 

        et_show = (EditText) this.findViewById(R.id.et_show); 

        bt_send = (Button) this.findViewById(R.id.bt_send); 

        try { 

            //定义客户连接的socket 

            Socket socket = new Socket("本机IP",30000); 

            //启动客户端监听线程 

            new Thread(new ClinetThread(socket,handler)).start(); 

            os = socket.getOutputStream(); 

        } catch (UnknownHostException e) { 

            e.printStackTrace(); 

        } catch (IOException e) { 

            e.printStackTrace(); 

        } 

        bt_send.setOnClickListener(new OnClickListener() { 

            @Override 

            public void onClick(View v) { 

                try { 

                    //得到输入框中的内容,写入到输入流中 

                    os.write((et_input.getText().toString()+"\r\n").getBytes("utf-8")); 

                    et_input.setText(""); 

                } catch (UnsupportedEncodingException e) { 

                    // TODO Auto-generated catch block 

                    e.printStackTrace(); 

                } catch (IOException e) { 

                    // TODO Auto-generated catch block 

                    e.printStackTrace(); 

                } 

            } 

        }); 

        handler = new Handler(){ 

            @Override 

            public void handleMessage(Message msg) { 

                super.handleMessage(msg); 

                if(msg.what == 1){ 

                    //得到服务器返回的信息 

                    et_show.append("\n"+msg.obj.toString()); 

                } 

            } 

        }; 

    } 

第三是客户端的线程类

[java] 

public class ClinetThread implements Runnable{ 

    Socket socket = null; 

    Handler handler = null; 

    BufferedReader br = null; 

    public ClinetThread(Socket socket,Handler handler) { 

        this.socket = socket; 

        this.handler = handler; 

        try { 

            br = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

        } catch (IOException e) { 

            e.printStackTrace(); 

        } 

    } 

    @Override 

    public void run() { 

        String content = null; 

        try { 

            while((content = br.readLine())!=null){ 

                Message msg = new Message(); 

                msg.what = 1; 

                msg.obj = content; 

                handler.sendMessage(msg); 

            } 

        } catch (IOException e) { 

            e.printStackTrace(); 

        } 

    } 

接下来是Java工程中的主类

[java] 

public class SimpleServer { 

    //定义保存所有Socket的ArrayList 

    public static ArrayList<Socket> socketList = new ArrayList<Socket>(); 

    public static void main(String[] args) { 

        try { 

            ServerSocket ss = new ServerSocket(30000); 

            while (true) { 

                Socket s = ss.accept(); 

                socketList.add(s); 

                new Thread(new ServerThead(s)).start(); 

            } 

        } catch (IOException e) { 

            e.printStackTrace(); 

        } 

    } 

其次java工程中的线程类

[java]

public class ServerThead implements Runnable { 

    //定义当前线程处理的socket 

    Socket s = null; 

    //该线程所处理的socket对应的输入流 

    BufferedReader br = null; 

    public ServerThead(Socket s) throws IOException { 

        this.s = s; 

        br = new BufferedReader(new InputStreamReader(s.getInputStream())); 

    } 

    @Override 

    public void run() { 

        String conntent = null; 

        while((conntent=readFromClient())!=null){ 

            //遍历socket中的每一个socket 

            for(Socket s:SimpleServer.socketList){ 

                try { 

                    OutputStream os = s.getOutputStream(); 

                    os.write((conntent+"\n").getBytes("utf-8")); 

                } catch (IOException e) { 

                    e.printStackTrace(); 

                } 

            } 

        } 

    } 

    private String readFromClient() { 

        try { 

            return br.readLine(); 

        } catch (IOException e) { 

            e.printStackTrace(); 

            SimpleServer.socketList.remove(s); 

        } 

        return null; 

    } 

}