android-------- socket 实现客户端与服务器端通信

前面介绍了Socket的简介和原理,今天简单的来实现一下客服端与服务器通信的功能

 

客服端

建立连接

 try {
socket
= new Socket("192.168.1.100", 9999); Log.i("Android", "与服务器建立连接:" + socket); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

 

发送消息

  try {
         // socket.getInputStream()
        DataOutputStream writer = new DataOutputStream(socket.getOutputStream());
        writer.writeUTF("嘿嘿,你好啊,服务器.."); // 写一个UTF-8的信息
        System.out.println("发送消息");
      } catch (IOException e) {
           e.printStackTrace();
      }

 

添加权限

 <uses-permission android:name="android.permission.INTERNET"/>

 

服务端(在Eclipse建立一个Java项目即可)

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        System.out.println("123456");
        startService();
    }
    
    
    /**  
    * 启动服务监听,等待客户端连接 
    */  
   private static void startService() {  
       try {  
           // 创建ServerSocket  
           ServerSocket serverSocket = new ServerSocket(9999);  
           System.out.println("--开启服务器,监听端口 9999--");  
 
           // 监听端口,等待客户端连接  
           while (true) {  
               System.out.println("--等待客户端连接--");  
               Socket socket = serverSocket.accept(); //等待客户端连接  
               System.out.println("得到客户端连接:" + socket);  
                 
               startReader(socket);  
           }  
 
       } catch (IOException e) {  
           e.printStackTrace();  
       }  
   }  
 
   /**  
    * 从参数的Socket里获取最新的消息 
    */  
   private static void startReader(final Socket socket) {  
 
       new Thread(){  
           @Override  
           public void run() {  
               DataInputStream reader;  
               try {  
                   // 获取读取流  
                   reader = new DataInputStream( socket.getInputStream());  
                   while (true) {  
                       System.out.println("*等待客户端输入*");  
                       // 读取数据  
                       String msg = reader.readUTF();  
                       System.out.println("获取到客户端的信息:" + msg);  
                   }  
               } catch (IOException e) {  
                   e.printStackTrace();  
               }  
           }  
       }.start();  
   }  

}

 

运行Java项目,得到

 

 

然后在手机端点击发送消息

     

 

 

服务端接收到消息,打印信息

 

 

服务端发送消息给客户端

 

服务端代码:

public class TestServer {

     public static void main(String[] args) {
        
         try {
            ServerSocket serverSocket = new ServerSocket(30000);
            System.out.println("服务器已连接");
            while(true){
                System.out.println("123");
                Socket socket = serverSocket.accept();
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write("你好,我是服务器\n".getBytes("utf-8"));
                outputStream.close();
                socket.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         
     }
}

 

客户端代码

public class Demo2Activity extends AppCompatActivity {

    static TextView textView;
    Socket socket;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo2);
        initView();
    }


    private void initView(){
        textView = (TextView) findViewById(R.id.txt_1);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket("192.168.1.101", 30000);
                    // socket.setSoTimeout(10000);//设置10秒超时
                    Log.i("Android", "与服务器建立连接:" + socket);
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String line = br.readLine();
                    Log.i("Android", "与服务器建立连接:" + line);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = line;
                    handler.sendMessage(msg);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1){
                textView.setText("这是来自服务器的数据:"+msg.obj.toString());
            }
        }
    };

}

 

 

先运行服务端,再运行客户端

效果图:

 

 

 

 

源码包含多个demo,也是参考网上资料而来

 

源码地址:https://github.com/DickyQie/android-socket

 

posted @ 2018-04-23 09:02  切切歆语  阅读(15446)  评论(1编辑  收藏  举报