android:Socket编程 模拟骂街

  所谓"骂街",就两个人"A","B"对骂,A骂B的过程是这样的: A发出信息---B接收信息--B处理信息(理解A骂的话,想着怎么回应A)--B发送

信息(反骂)--A接收信息--A处理信息(理解B骂的话,想着怎么回应B)。循环这个过程。

  客户端:

 

  1 package com.example.csserver;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.BufferedWriter;
  5 import java.io.IOException;
  6 import java.io.InputStreamReader;
  7 import java.io.OutputStreamWriter;
  8 import java.net.Socket;
  9 
 10 import java.util.Timer;
 11 import java.util.TimerTask;
 12 
 13 import android.app.Activity;
 14 import android.os.Bundle;
 15 import android.os.Handler;
 16 import android.os.Message;
 17 
 18 import android.view.View;
 19 import android.view.View.OnClickListener;
 20 import android.widget.Button;
 21 import android.widget.EditText;
 22 
 23 public class MainActivity extends Activity {
 24 
 25     public EditText et_client;
 26     private EditText et_ip;
 27     private EditText et_port;
 28     public EditText et_service;
 29     public Button bt_send;
 30     private Button bt_stop;
 31     public String clientText;
 32     private String host=null ;
 33     private int port=0 ;
 34     private BufferedReader br;
 35     private BufferedWriter bw;
 36     Timer timer=null;
 37 
 38     @Override
 39     public void onCreate(Bundle savedInstanceState) {
 40         super.onCreate(savedInstanceState);
 41         setContentView(R.layout.activity_main);
 42         et_ip=(EditText)findViewById(R.id.et_ip);
 43         et_port=(EditText)findViewById(R.id.et_port);
 44         bt_stop=(Button)findViewById(R.id.bt_stop);
 45         et_client = (EditText) findViewById(R.id.et_client);
 46         et_service = (EditText) findViewById(R.id.et_service);
 47         bt_send = (Button) findViewById(R.id.bt_send);
 48         
 49         bt_send.setOnClickListener(new OnClickListener() {
 50 
 51             @Override
 52             public void onClick(View v) {
 53                 host=et_ip.getText().toString().trim();
 54                 port=Integer.parseInt(et_port.getText().toString().trim());
 55                 clientText = et_client.getText().toString();
 56                 sendTimer();
 57 
 58             }
 59         });
 60         bt_stop.setOnClickListener(new OnClickListener() {
 61             
 62             @Override
 63             public void onClick(View v) {
 64                 
 65                      if (task != null) {
 66                          task.cancel();
 67                          task = null;
 68                      }
 69                      if (timer != null) {
 70                          timer.cancel();
 71                          timer.purge();
 72                          timer = null;
 73                      }
 74 
 75                 
 76             }
 77         });
 78         
 79     }
 80     
 81     /**
 82      * 接收服务器返回的数据
 83      * @param receiveSocket
 84      * @return
 85      * @throws IOException
 86      */
 87     private String receiveData(Socket receiveSocket) throws IOException {
 88          br = new BufferedReader(new InputStreamReader(
 89                 receiveSocket.getInputStream()));
 90         String receiveStr = br.readLine();
 91         br.close();
 92         return receiveStr;
 93 
 94     }
 95     /**
 96      * 向服务器发送数据
 97      * @param sendSocket
 98      * @param sendText
 99      */
100     private void transData(Socket sendSocket, String sendText) {
101         try {
102              bw = new BufferedWriter(new OutputStreamWriter(
103                     sendSocket.getOutputStream()));
104             bw.write(sendText.replace("\n", " ") + "\n");
105             bw.flush();
106         
107         } catch (IOException e) {
108             // TODO 自动生成的 catch 块
109             e.printStackTrace();
110         }
111     }
112     /**
113      * 创建客户端Socket
114      * @param host
115      * @param port
116      * @return
117      * @throws IOException
118      * @throws IOException
119      */
120     private Socket requestSocket(String host, int port) throws IOException,
121             IOException {
122         Socket socket = new Socket(host, port);
123         return socket;
124     }
125     /**    
126      * 关闭Socket
127      * 注意:"流可以关 但要等到服务器验证完毕后再关  尤其是你的输出流 "
128      * @param socket
129      * @throws IOException
130      */
131     private void closeSocket(Socket socket) throws IOException{
132         br.close();
133         bw.close();
134         socket.close();
135         
136     }
137     Handler timerHandler = new Handler() {
138         public void handleMessage(Message msg) {
139             Bundle bd = msg.getData();
140             if (msg.what == 1) {
141 
142                 et_service.setText(bd.getString("data"));
143 
144             }
145             super.handleMessage(msg);
146         }
147     };
148 
149     TimerTask task = new TimerTask() {
150 
151         public void run() {
152             Message message = new Message();
153             message.what = 1;
154             try {
155                 Socket socket = requestSocket(host, port);
156                 transData(socket, clientText);
157                 String showText = receiveData(socket);
158                 closeSocket(socket);
159                 Bundle bundle = new Bundle();
160                 bundle.putString("data", showText);
161                 message.setData(bundle);
162                 timerHandler.sendMessage(message);
163             } catch (IOException e) {
164                 // TODO 自动生成的 catch 块
165                 e.printStackTrace();
166             }
167 
168         }
169     };
170     
171     private void sendTimer() {
172         timer=new Timer();
173         timer.schedule(task, 1000, 400);
174     }
175 }
176 
177  

  服务端:

  1 package com.test;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.BufferedWriter;
  5 import java.io.IOException;
  6 import java.io.InputStreamReader;
  7 import java.io.OutputStreamWriter;
  8 import java.net.ServerSocket;
  9 import java.net.Socket;
 10 
 11 public class Test extends Thread {
 12     private  int i=0;
 13 
 14 private Test() throws IOException {
 15    CreateSocket();
 16    //创建Socket服务器
 17 } 
 18 
 19 public void run() { 
 20    Socket client;
 21    String txt;
 22    try { 
 23     while (true)
 24     //线程无限循环,实时监听socket端口
 25     {
 26      client=ResponseSocket();       
 27      //响应客户端链接请求。。
 28     
 29      while(true)
 30      {
 31       txt=ReceiveMsg(client);  
 32       System.out.println(txt);
 33       //链接获得客户端发来消息,并将其显示在Server端的屏幕上
 34    
 35       SendMsg(client,txt);
 36       //向客户端返回消息
 37 
 38       if(true)break;
 39       //中断,继续等待链接请求
 40      }
 41     
 42      CloseSocket(client);
 43      //关闭此次链接
 44     }   
 45    } 
 46    catch (IOException e) {
 47     System.out.println(e);
 48    }
 49 
 50 }
 51 
 52 private ServerSocket server = null;
 53 private static final int PORT = 2000;
 54 private BufferedWriter writer;
 55 private BufferedReader reader;
 56 
 57 private void CreateSocket() throws IOException
 58 {
 59    server = new ServerSocket(PORT, 100);
 60    System.out.println("Server starting..");  
 61 }
 62 
 63 private Socket ResponseSocket() throws IOException
 64 {
 65    Socket client = server.accept(); 
 66    System.out.println("client connected..");
 67   
 68    return client;
 69 }
 70 
 71 private void CloseSocket(Socket socket) throws IOException
 72 {
 73    reader.close();
 74    writer.close();
 75    socket.close();
 76    System.out.println("client closed..");
 77 }
 78 
 79 private void SendMsg(Socket socket,String Msg) throws IOException 
 80 {
 81    writer = new BufferedWriter(
 82       new OutputStreamWriter(socket.getOutputStream()));
 83    i++;
 84     writer.write(Msg+i+"\n");
 85     writer.flush();
 86    
 87 }
 88 
 89 private String ReceiveMsg(Socket socket) throws IOException
 90 {
 91    reader = new BufferedReader(
 92      new InputStreamReader(socket.getInputStream()));     
 93     System.out.println("server get input from client socket..");
 94     String txt="client send:"+reader.readLine();
 95    
 96     return txt;
 97 }
 98 
 99 public static void main(final String args[]) throws IOException {
100     Test yaochatserver = new Test();
101    if (yaochatserver != null) {
102     yaochatserver.start();
103    }
104 }
105 
106 }

  布局文件:

 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_service"
 8         android:layout_width="fill_parent"
 9         android:layout_height="50dp"
10         android:layout_alignParentBottom="true"
11         android:layout_alignParentLeft="true"
12         android:layout_marginTop="109dp"
13         android:text="准备接受信息" />
14 
15     <Button
16         android:id="@+id/bt_stop"
17         android:layout_width="wrap_content"
18         android:layout_height="wrap_content"
19         android:layout_alignParentLeft="true"
20         android:layout_centerVertical="true"
21         android:text="停止发送" />
22 
23     <Button
24         android:id="@+id/bt_send"
25         android:layout_width="wrap_content"
26         android:layout_height="wrap_content"
27         android:layout_alignBaseline="@+id/bt_stop"
28         android:layout_alignBottom="@+id/bt_stop"
29         android:layout_alignParentRight="true"
30         android:text="发送信息" />
31 
32     <TextView
33         android:id="@+id/textView1"
34         android:layout_width="wrap_content"
35         android:layout_height="wrap_content"
36         android:layout_alignParentLeft="true"
37         android:layout_alignParentTop="true"
38         android:text="配置服务器地址:"
39         android:textSize="23dp" />
40 
41     <EditText
42         android:id="@+id/et_ip"
43         android:layout_width="wrap_content"
44         android:layout_height="wrap_content"
45         android:layout_alignParentRight="true"
46         android:layout_alignParentTop="true"
47         android:text="192.168.0.196" >
48 
49         
50     EditText>
51 
52     <EditText
53         android:id="@+id/et_client"
54         android:layout_width="fill_parent"
55         android:layout_height="wrap_content"
56         android:layout_above="@+id/bt_stop"
57         android:layout_alignParentLeft="true"
58         android:layout_marginBottom="46dp"
59         android:hint="请输入发送的内容" />
60 
61     <TextView
62         android:id="@+id/textView1"
63         android:layout_width="wrap_content"
64         android:layout_height="wrap_content"
65         android:layout_alignParentLeft="true"
66         android:layout_below="@+id/et_ip"
67         android:text="配置服务器端口:"
68         android:textSize="23dp" />
69 
70     <EditText
71         android:id="@+id/et_port"
72         android:layout_width="wrap_content"
73         android:layout_height="wrap_content"
74         android:layout_alignLeft="@+id/bt_send"
75         android:layout_alignTop="@+id/textView1"
76         android:text="2000" />
77 
78 RelativeLayout>

  

  最开始编写时我遇到了一个稀奇古怪的问题,我的客户端在模拟器上时一切正常;当在真实的android客户端上时,服务器能收到客户端发送的信息,而客户端接收不到服务器返回的信息,我以为是防火墙或者局域网搞的怪,但跟为奇怪的是在调试模式下客户端还能收的服务器放回的信息,后来我更改了客户端发送和接收的处理流程问题得到了解决

 

 

转载于:https://www.cnblogs.com/sunfb/archive/2012/11/14/S_Fbuner.html

你可能感兴趣的:(android:Socket编程 模拟骂街)