Android socket编程



      Socket通常也称做”套接字“,用于描述IP地址和端口,它就是网络通信过程中端点的抽象表示。Java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。

  • SocketServer类,服务器实现:
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();              }          }      }  }
public class TestSocketServer {            public static void main(String[] argvs){          SocketServer server = new SocketServer(12345);          server.beginListen();      }  }

客户端实现:
public class SocketClientDemo extends Activity implements Runnable {     private TextView tv_msg = null;     private EditText ed_msg = null;     private Button btn_send = null;     private static final String HOST = "192.168.1.223";     private static final int PORT = 12345;     private Socket socket = null;     private BufferedReader in = null;     private PrintWriter out = null;     private String content = "";      /** Called when the activity is first created. */     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);          tv_msg = (TextView) findViewById(R.id.TextView);         ed_msg = (EditText) findViewById(R.id.EditText01);         btn_send = (Button) findViewById(R.id.Button01);          try {             socket = new Socket(HOST, PORT);             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));             out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(                     socket.getOutputStream())), true);         } catch (IOException ex) {             ex.printStackTrace();             ShowDialog("login exception" + ex.getMessage());         }         btn_send.setOnClickListener(new Button.OnClickListener() {              @Override             public void onClick(View v) {                 // TODO Auto-generated method stub                 String msg = ed_msg.getText().toString();                 if (socket.isConnected()) {                     if (!socket.isOutputShutdown()) {                         out.println(msg);                     }                 }             }         });         new Thread(SocketDemo.this).start();     }      public void run() {         try {             while (true) {                 if (socket.isConnected()) {                     if (!socket.isInputShutdown()) {                         if ((content = in.readLine()) != null) {                             content += "\n";                             Log.d("socket","socket:"+content);                         } else {                          }                     }                 }             }         } catch (Exception e) {             e.printStackTrace();         }     }  } 

注意在AndroidManifest.xml中加入对网络的访问权限

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




     本文转自xyz_lmn51CTO博客,原文链接:http://blog.51cto.com/xyzlmn/1230758,如需转载请自行联系原作者



上一篇:采用全面的数据中心保护解决方案提高系统可靠性


下一篇:桌面虚拟化之数据库高可用性