当前位置:操作系统 > 安卓/Android >>

android-->Socket简单用法

Socket通常也称做”套接字“,用于描述IP地址和端口,废话不多说,它就是网络通信过程中端点的抽象表示。值得一提的是,Java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用起来很方便!
    下面将首先创建一个SocketServer的类作为服务端如下,该服务端实现了多线程机制,可以在特定端口处监听多个客户请求,一旦有客户请求,Server总是会创建一个服务纯种来服务新来的客户,而自己继续监听。程序中accept()是一个阻塞函数,所谓阻塞性方法就是说该方法被调用后将等待客户的请求,直到有一个客户启动并请求连接到相同的端口,然后accept()返回一个对应于客户的Socket。这时,客户方和服务方都建立了用于通信的Socket,接下来就是由各个Socket分别打开各自的输入、输出流。
SocketServer类,服务器实现:
[java] 
package HA.Socket; 
  
 import java.io.*; 
 import java.net.*; 
  
  public class SocketServer { 
      
     ServerSocket sever; 
      
     public SocketServer(int port){ 
         try{ 
             sever = new ServerSocket(port); 
         }catch(IOException e){ 
             e.printStackTrace(); 
         } 
     } 
      
     public void beginListen(){ 
         while(true){ 
             try{ 
                 final Socket socket = sever.accept(); 
                  
                 new Thread(new Runnable(){ 
                     public void run(){ 
                         BufferedReader in; 
                         try{ 
                             in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8")); 
                             PrintWriter out = new PrintWriter(socket.getOutputStream()); 
                             while (!socket.isClosed()){ 
                                 String str; 
                                 str = in.readLine(); 
                                 out.println("Hello!world!! " + str); 
                                 out.flush(); 
                                 if (str == null || str.equals("end")) 
                                     break; 
                                 System.out.println(str); 
                             } 
                             socket.close(); 
                         }catch(IOException e){ 
                             e.printStackTrace(); 
                         } 
                     } 
                 }).start(); 
             }catch(IOException e){ 
                 e.printStackTrace(); 
             } 
         } 
     } 
 } 
 
SocketClient类,客户端实现:
[java] 
package HA.Socket; 
  
 import java.io.*; 
 import java.net.*; 
  
  public class SocketClient { 
     static Socket client; 
      
     public SocketClient(String site, int port){ 
         try{ 
             client = new Socket(site,port); 
             System.out.println("Client is created! site:"+site+" port:"+port); 
         }catch (UnknownHostException e){ 
             e.printStackTrace(); 
         }catch (IOException e){ 
             e.printStackTrace(); 
 &

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,