目录:

一、效果图

二、原代码分享

三、代码分析

四、总结

 

 

一、效果图如下

客户端1:                            客户端2:   

12、android socket使用demo:网络聊天         12、android socket使用demo:网络聊天

 

二、原代码分享如下:

1、java代码只有一个

MainActivity.java

  1 package com;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStreamReader;
  6 import java.io.OutputStream;
  7 import java.io.UnsupportedEncodingException;
  8 import java.net.ServerSocket;
  9 import java.net.Socket;
 10 import java.util.ArrayList;
 11 
 12 import android.app.Activity;
 13 import android.os.Bundle;
 14 import android.os.Handler;
 15 import android.os.Message;
 16 import android.view.View;
 17 import android.view.View.OnClickListener;
 18 import android.widget.Button;
 19 import android.widget.CheckBox;
 20 import android.widget.CompoundButton;
 21 import android.widget.CompoundButton.OnCheckedChangeListener;
 22 import android.widget.EditText;
 23 import android.widget.TextView;
 24 
 25 import com.example.androidsockettest.R;
 26 
 27 public class MainActivity extends Activity{
 28 
 29     private Button button_send = null;
 30     private EditText et_ip = null;
 31     private EditText et_port = null;
 32     private EditText et_conent = null;
 33     private TextView tv_history = null;
 34     private CheckBox checkBoxSwitch = null;
 35     private static int defaultPort = 8888;
 36     public static ArrayList<Socket> socketList=new ArrayList<Socket>();
 37     
 38     private OutputStream out=null;
 39     private Handler handler = null;
 40     private Socket s = null;
 41     String tag = "chatRoom";
 42     private BufferedReader buRead = null;
 43     
 44     private final int UPDATE_HISTORY_CONTENT = 0;
 45     private final int UPDATE_INPUT_CONTENT = 1;
 46     
 47     @Override
 48     protected void onCreate(Bundle savedInstanceState) {
 49         // TODO Auto-generated method stub
 50         super.onCreate(savedInstanceState);
 51         setContentView(R.layout.main_activity);
 52         
 53         init();
 54         
 55         configure();
 56         
 57         serverStart();
 58     }
 59     
 60     @Override
 61     protected void onDestroy() {
 62         // TODO Auto-generated method stub
 63         super.onDestroy();
 64     }
 65     
 66     
 67     public void init()
 68     {
 69         button_send = (Button)findViewById(R.id.button_send);
 70         et_ip = (EditText)findViewById(R.id.editText_ip);
 71         et_port = (EditText)findViewById(R.id.EditText_port);
 72         et_conent = (EditText)findViewById(R.id.EditText_content);
 73         tv_history = (TextView)findViewById(R.id.textView_history_content);
 74         checkBoxSwitch = (CheckBox)findViewById(R.id.checkBox_server_start);
 75     }
 76     
 77     
 78     public void configure()
 79     {
 80         button_send.setOnClickListener(new OnClickListener() {
 81             
 82             @Override
 83             public void onClick(View v) {
 84                 // TODO Auto-generated method stub
 85                 try {
 86                     String content = et_conent.getText().toString();//读取用户输入文本
 87                     
 88                     if(out == null)
 89                     {
 90                         CommonUtils.LogWuwei(tag,"the fucking out is null");
 91                         return;
 92                     }
 93                     
 94                     out.write((content+"\n").getBytes("utf-8"));//写入socket
 95                     
 96                     String history_content = tv_history.getText().toString();
 97                     history_content+="你说:"+et_conent.getText()+"\n";
 98                     
 99                     
100                     Message msg = new Message();
101                     msg.what = UPDATE_HISTORY_CONTENT;
102                     msg.obj = history_content;
103                     handler.sendMessage(msg);
104                     
105                     msg = new Message();
106                     msg.what = UPDATE_INPUT_CONTENT;
107                     msg.obj = "";
108                     handler.sendMessage(msg);
109                     
110                     
111                     CommonUtils.LogWuwei(tag, "send success");
112                 } catch (UnsupportedEncodingException e) {
113                     // TODO Auto-generated catch block
114                     e.printStackTrace();
115                     CommonUtils.LogWuwei(tag, "send failed "+e.getMessage());
116                 } catch (IOException e) {
117                     // TODO Auto-generated catch block
118                     e.printStackTrace();
119                     CommonUtils.LogWuwei(tag, "send failed "+e.getMessage());
120                 }
121             }
122         });
123         
124         
125         checkBoxSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
126             
127             @Override
128             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
129                 // TODO Auto-generated method stub
130                 if(isChecked)
131                 {
132                     CommonUtils.LogWuwei(tag, "clientStart");
133                     clientStart();
134                 }
135                 else
136                 {
137                     CommonUtils.LogWuwei(tag, "clientStop");
138                     clientStop();
139                 }
140             }
141         });
142         
143         
144         handler = new Handler()
145         {
146             @Override
147             public void handleMessage(Message msg) {
148                 // TODO Auto-generated method stub
149                 super.handleMessage(msg);
150                 switch (msg.what)
151                 {
152                 case UPDATE_HISTORY_CONTENT:
153                     CommonUtils.LogWuwei(tag, "更新历史记录"+msg.obj);
154                     tv_history.setText((String)msg.obj);
155                     break;
156                     
157                 case UPDATE_INPUT_CONTENT:
158                     CommonUtils.LogWuwei(tag, "清空输入记录");
159                     et_conent.setText("");//清空文本
160                     break;
161                 }
162             }
163         };
164         
165     }
166     
167     
168     public void serverStart()
169     {
170         try {
171             
172             final ServerSocket ss = new ServerSocket(defaultPort);
173 
174             CommonUtils.LogWuwei(tag, "on serverStart");
175             
176             new Thread()
177             {
178                 public void run()
179                 {
180                     while(true)
181                     {
182                         try {
183                             CommonUtils.LogWuwei(tag, "on serverStart: ready to accept");
184                             s=ss.accept();
185                             socketList.add(s);
186                             buRead = new BufferedReader(new InputStreamReader(s.getInputStream(), "utf-8"));
187                             
188                             String receive_content = null;
189                             while ((receive_content=readFromClient())!=null) {
190                                 CommonUtils.LogWuwei(tag,"客户端说:"+receive_content);
191                                 
192                                 String history_content = tv_history.getText().toString();
193                                 history_content+=s.getInetAddress()+"说:"+receive_content+"\n";
194                                 
195                                 Message msg = new Message();
196                                 msg.what = UPDATE_HISTORY_CONTENT;
197                                 msg.obj = history_content;
198                                 handler.sendMessage(msg);
199                                 
200                                 
201                                 for (Socket ss:socketList) 
202                                 {
203                                     OutputStream out=ss.getOutputStream();
204                                     out.write(("[服务器已经收到消息]"+"\n").getBytes("utf-8"));
205                                 }
206                             }
207                             
208                             
209                         } catch (UnsupportedEncodingException e) {
210                             // TODO Auto-generated catch block
211                             e.printStackTrace();
212                         } catch (IOException e) {
213                             // TODO Auto-generated catch block
214                             e.printStackTrace();
215                         }
216                         
217                     }
218                 }
219             }.start();
220             
221         } catch (IOException e) {
222             // TODO Auto-generated catch block
223             e.printStackTrace();
224         }
225         
226     }
227     
228     
229     private String readFromClient(){
230         try {
231             return buRead.readLine();
232         } catch (Exception e) {
233             //删除此Socket
234             socketList.remove(s);
235         }
236         return null;
237     }
238     
239     
240     public void clientStart()
241     {
242         new Thread(new Runnable() {
243                 
244                 @Override
245                 public void run() {
246                     try {
247                         String ip = et_ip.getText().toString();
248                         String port = et_port.getText().toString();
249                         
250                         if(!port.equals("") && port != null)
251                         {
252                             s=new Socket(ip, defaultPort);    
253                         }
254                         else
255                         {
256                             s=new Socket(ip, Integer.parseInt(port));
257                         }
258                         
259                         out=s.getOutputStream();
260                         CommonUtils.LogWuwei(tag, "clientStart success");
261                         
262                     } catch (IOException e) {
263                         e.printStackTrace();
264                         CommonUtils.LogWuwei(tag, "clientStart failed "+e.getMessage());
265                     }
266                 }
267             }).start();
268         
269         
270     }
271 
272 
273     public void clientStop()
274     {
275         try {
276             if(s != null)
277                 s.close();
278             if(out != null)
279                 out.close();
280             
281         } catch (IOException e) {
282             // TODO Auto-generated catch block
283             e.printStackTrace();
284         }
285         
286         
287     }
288 
289 }
View Code

相关文章:

  • 2021-05-01
  • 2021-07-24
  • 2022-12-23
  • 2021-12-20
  • 2022-12-23
  • 2021-08-30
  • 2021-06-30
  • 2021-10-01
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-05
  • 2021-07-05
  • 2022-02-01
  • 2021-06-02
  • 2021-07-17
相关资源
相似解决方案