android实现简单的聊天室

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

首先还是android的内容


[html]  view plain copy print ?
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.   
  6.     <EditText  
  7.         android:id="@+id/et_show"  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:lines="5"  
  11.         android:hint="所有聊天信息"  
  12.         android:gravity="center"  
  13.          />  
  14.     <EditText  
  15.         android:id="@+id/et_input"  
  16.         android:layout_below="@+id/et_show"  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:hint="输入聊天信息"  
  20.         android:gravity="center"  
  21.          />  
  22.     <Button   
  23.         android:id="@+id/bt_send"  
  24.         android:layout_below="@+id/et_input"  
  25.         android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:text="发送信息"  
  28.         />  
  29. </RelativeLayout>  

接着是MainAvitvity.java



[java]  view plain copy print ?
  1. public class MainActivity extends Activity {  
  2.       
  3.     private EditText et_show,et_input;  
  4.     private Button bt_send;  
  5.     private OutputStream os;  
  6.     private Handler handler;  
  7.   
  8.     @Override  
  9.     protected void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.activity_main);  
  12.           
  13.         et_input = (EditText) this.findViewById(R.id.et_input);  
  14.         et_show = (EditText) this.findViewById(R.id.et_show);  
  15.         bt_send = (Button) this.findViewById(R.id.bt_send);  
  16.           
  17.           
  18.         try {  
  19.             //定义客户连接的socket  
  20.             Socket socket = new Socket("本机IP",30000);  
  21.             //启动客户端监听线程  
  22.             new Thread(new ClinetThread(socket,handler)).start();  
  23.             os = socket.getOutputStream();  
  24.         } catch (UnknownHostException e) {  
  25.             e.printStackTrace();  
  26.         } catch (IOException e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.           
  30.           
  31.         bt_send.setOnClickListener(new OnClickListener() {  
  32.             @Override  
  33.             public void onClick(View v) {  
  34.                 try {  
  35.                     //得到输入框中的内容,写入到输入流中  
  36.                     os.write((et_input.getText().toString()+"\r\n").getBytes("utf-8"));  
  37.                     et_input.setText("");  
  38.                 } catch (UnsupportedEncodingException e) {  
  39.                     // TODO Auto-generated catch block  
  40.                     e.printStackTrace();  
  41.                 } catch (IOException e) {  
  42.                     // TODO Auto-generated catch block  
  43.                     e.printStackTrace();  
  44.                 }  
  45.             }  
  46.         });  
  47.           
  48.           
  49.         handler = new Handler(){  
  50.             @Override  
  51.             public void handleMessage(Message msg) {  
  52.                 super.handleMessage(msg);  
  53.                 if(msg.what == 1){  
  54.                     //得到服务器返回的信息  
  55.                     et_show.append("\n"+msg.obj.toString());  
  56.                 }  
  57.             }  
  58.         };  
  59.     }  
  60.       
  61. }  

第三是客户端的线程类



[java]  view plain copy print ?
  1. public class ClinetThread implements Runnable{  
  2.   
  3.     Socket socket = null;  
  4.     Handler handler = null;  
  5.       
  6.     BufferedReader br = null;  
  7.       
  8.     public ClinetThread(Socket socket,Handler handler) {  
  9.         this.socket = socket;  
  10.         this.handler = handler;  
  11.         try {  
  12.             br = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
  13.         } catch (IOException e) {  
  14.             e.printStackTrace();  
  15.         }  
  16.           
  17.     }  
  18.       
  19.     @Override  
  20.     public void run() {  
  21.         String content = null;  
  22.         try {  
  23.             while((content = br.readLine())!=null){  
  24.                 Message msg = new Message();  
  25.                 msg.what = 1;  
  26.                 msg.obj = content;  
  27.                 handler.sendMessage(msg);  
  28.             }  
  29.         } catch (IOException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
  33.       
  34. }  

接下来是Java工程中的主类



[java]  view plain copy print ?
  1. /** 
  2.  * 创建ServerSocket监听的主类 
  3.  * 该类只负责接收客户端的socket连接请求,每当客户端 
  4.  * 连接到该serversocket之后,程序将对应socket加入到list 
  5.  * 并为该socket开一挑单独的线程,负责socket的所有通信任务 
  6.  * @author Administrator 
  7.  * 
  8.  */  
  9. public class SimpleServer {  
  10.       
  11.     //定义保存所有Socket的ArrayList  
  12.     public static ArrayList<Socket> socketList = new ArrayList<Socket>();  
  13.       
  14.     public static void main(String[] args) {  
  15.         try {  
  16.             ServerSocket ss = new ServerSocket(30000);  
  17.             while (true) {  
  18.                 Socket s = ss.accept();  
  19.                 socketList.add(s);  
  20.                 new Thread(new ServerThead(s)).start();  
  21.             }  
  22.         } catch (IOException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.           
  26.     }  
  27. }  

其次java工程中的线程类



[java]  view plain copy print ?
  1. /** 
  2.  * 负责每个线程通信的类 
  3.  * 该类不断读取客户端数据,使用自定义的readFromClient()方法读取 
  4.  * 客户端数据,如果出现异常表明该socket对应的客户端socket出现了问题 
  5.  * 程序将该socket从list中移除。 
  6.  * 当服务器线程读取到了客户端数据后,遍历list集合,并将数据发送到每个 
  7.  * socket中 
  8.  * @author Administrator 
  9.  * 
  10.  */  
  11. public class ServerThead implements Runnable {  
  12.   
  13.     //定义当前线程处理的socket  
  14.     Socket s = null;  
  15.     //该线程所处理的socket对应的输入流  
  16.     BufferedReader br = null;  
  17.       
  18.     public ServerThead(Socket s) throws IOException {  
  19.         this.s = s;  
  20.         br = new BufferedReader(new InputStreamReader(s.getInputStream()));  
  21.     }  
  22.   
  23.     @Override  
  24.     public void run() {  
  25.         String conntent = null;  
  26.         while((conntent=readFromClient())!=null){  
  27.             //遍历socket中的每一个socket  
  28.             for(Socket s:SimpleServer.socketList){  
  29.                 try {  
  30.                     OutputStream os = s.getOutputStream();  
  31.                     os.write((conntent+"\n").getBytes("utf-8"));  
  32.                 } catch (IOException e) {  
  33.                     e.printStackTrace();  
  34.                 }  
  35.                   
  36.             }  
  37.         }  
  38.     }  
  39.   
  40.     private String readFromClient() {  
  41.         try {  
  42.             return br.readLine();  
  43.         } catch (IOException e) {  
  44.             e.printStackTrace();  
  45.             SimpleServer.socketList.remove(s);  
  46.         }  
  47.         return null;  
  48.     }  
  49.   
  50. }  
  51. 转载请标明出处:雅荷湾

转载于:https://my.oschina.net/hpujsj/blog/88127

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值