Android中的socket

客户端:

    package com.zx.android;  
    import android.app.Activity;  
    import android.os.Bundle;  
    import android.util.Log;  
    import android.view.View;  
    import android.view.View.OnClickListener;  
    import android.widget.Button;  
    import android.widget.EditText;  
    import android.widget.TextView;  
    import android.content.Context;  
    import android.widget.Toast;  
    import java.io.BufferedReader;  
    import java.io.BufferedWriter;  
    import java.io.InputStreamReader;  
    import java.io.OutputStreamWriter;  
    import java.io.PrintWriter;  
    import android.net.wifi.WifiManager;  
    import java.net.Socket;  
    import com.zx.android.ClientActivity;  
    public class ClientActivity extends Activity {  
        /** Called when the activity is first created. */  
        private Button startButton = null;  
         private Button stopButton = null;  
         private Button checkButton = null;  
         private WifiManager wifiManager = null;  
         private final String   DEBUG_TAG= "Activity01";  
         private TextView   mTextView=null;  
         private EditText   mEditText=null;  
         private Button     mButton=null;  
      
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
          super.onCreate(savedInstanceState);  
          setContentView(R.layout.main);  
            mButton = (Button)findViewById(R.id.Button01);  
            mTextView=(TextView)findViewById(R.id.TextView01);  
            mEditText=(EditText)findViewById(R.id.EditText01);  
          startButton = (Button)findViewById(R.id.startWifi);  
          stopButton = (Button)findViewById(R.id.stopWifi);  
          checkButton = (Button)findViewById(R.id.checkWifi);  
          startButton.setOnClickListener(new StartWifiListener());  
          stopButton.setOnClickListener(new StopWifiListener());  
          checkButton.setOnClickListener(new CheckWifiListener());  
        
        //登陆  
        mButton.setOnClickListener(new OnClickListener()  
        {  
            public void onClick(View v)  
            {  
                Socket socket = null;  
                String message = mEditText.getText().toString() + "/r/n";   
                try   
                {     
                    //创建Socket  
                    socket = new Socket("192.168.1.102",54321);   
                    //向服务器端发送消息  
                    PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);        
                    out.println(message);   
                      
                    //接收来自服务器端的消息  
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));   
                    String msg = br.readLine();   
                      
                    if ( msg != null )  
                    {  
                        mTextView.setText(msg);  
                    }  
                    else  
                    {  
                        mTextView.setText("数据错误!");  
                    }  
                    //关闭流  
                    out.close();  
                    br.close();  
                    //关闭Socket  
                    socket.close();   
                }  
                catch (Exception e)   
                {  
                    // TODO: handle exception  
                    Log.e(DEBUG_TAG, e.toString());  
                }  
            }  
        });  
    }  
      class StartWifiListener implements OnClickListener{  
          public void onClick(View v) {  
           wifiManager = (WifiManager)ClientActivity.this.getSystemService(Context.WIFI_SERVICE);  
           wifiManager.setWifiEnabled(true);  
           System.out.println("wifi state --->" + wifiManager.getWifiState());  
           Toast.makeText(ClientActivity.this, "当前Wifi网卡状态为" +   
        wifiManager.getWifiState(), Toast.LENGTH_SHORT).show();  
          }  
            }  
      class StopWifiListener implements OnClickListener{  
          public void onClick(View arg0) {  
           wifiManager = (WifiManager)ClientActivity.this.getSystemService(Context.WIFI_SERVICE);  
           wifiManager.setWifiEnabled(false);  
           System.out.println("wifi state --->" + wifiManager.getWifiState());  
           Toast.makeText(ClientActivity.this, "当前Wifi网卡状态为" +   
        wifiManager.getWifiState(), Toast.LENGTH_SHORT).show();  
          }  
              
            }  
              
      class CheckWifiListener implements OnClickListener{  
          public void onClick(View v) {  
           wifiManager = (WifiManager)ClientActivity.this.getSystemService(Context.WIFI_SERVICE);  
           System.out.println("wifi state --->" + wifiManager.getWifiState());  
           Toast.makeText(ClientActivity.this, "当前Wifi网卡状态为" +   
        wifiManager.getWifiState(), Toast.LENGTH_SHORT).show();  
          }  
               
            }  
    }  

  这个是我在手机上运行时截的图,下面三个按钮是操作wifi网关的按钮,下面的那个提示框是按下这个按钮出现的,数字为0表示正在关闭wifi,数字2表示正在开启wifi,数字1表示wifi处于关闭状态,数字3表示 wifi处于开启状态。

      上面的的发送按钮可以发送数据到服务器,实验室的是局域网,没有无线网络,我利用一个无线路由与电脑相连,在利用手机wifi搜索到该网络,手机与电脑构成局域网,便可发送数据。至于服务器端,可以采用网络调试助手接收数据,协议选择TCP服务器,ip地址和端口视自己情况定。

       当然也可以自己写个服务器端程序,再在命令行窗口中显示接收到的数据。

服务器端程序如下:

    package com.zx.android;  
    import java.io.BufferedReader;  
    import java.io.BufferedWriter;  
    import java.io.InputStreamReader;  
    import java.io.OutputStreamWriter;  
    import java.io.PrintWriter;  
    import java.net.ServerSocket;  
    import java.net.Socket;  
    public class Server implements Runnable  
    {  
        public void run()  
        {  
            try  
            {  
                //创建ServerSocket  
                ServerSocket serverSocket = new ServerSocket(54321);  
                while (true)  
                {  
                    //接受客户端请求  
                    Socket client = serverSocket.accept();  
                    System.out.println("accept");  
                    try  
                    {  
                        //接收客户端消息  
                        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));  
                        String str = in.readLine();  
                        System.out.println("read:" + str);      
                        //向服务器发送消息  
                        PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);        
                        out.println("server message");   
                        //关闭流  
                        out.close();  
                        in.close();  
                    }  
                    catch (Exception e)  
                    {  
                        System.out.println(e.getMessage());  
                        e.printStackTrace();  
                    }  
                    finally  
                    {  
                        //关闭  
                        client.close();  
                        System.out.println("close");  
                    }  
                }  
            }  
            catch (Exception e)  
            {  
                System.out.println(e.getMessage());  
            }  
        }  
        //main函数,开启服务器  
        public static void main(String[] args)  
        {  
            Thread desktopServerThread = new Thread(new Server());  
            desktopServerThread.start();  
        }  
    }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值