socket

参考 http://www.cnblogs.com/skynet/archive/2010/12/12/1903949.html

http://haohaoxuexi.iteye.com/blog/1979837

本质

服务端往Socket的输出流里面写东西,客户端就可以通过Socket的输入流读取对应的内容。SocketSocket之间是双向连通的,所以客户端也可以往对应的Socket输出流里面写东西,然后服务端对应的Socket的输入流就可以读出对应的内容

实现

对于Java Socket编程而言,有两个概念,一个是ServerSocket,一个是Socket。服务端和客户端之间通过Socket建立连接,之后它们就可以进行通信了。首先ServerSocket将在服务端监听某个端口,当发现客户端有Socket来试图连接它时,它会acceptSocket的连接请求,同时在服务端建立一个对应的Socket与之进行通信。这样就有两个Socket了,客户端和服务端各一个。

public class Server {
 
   public static void main(String args[]) throws IOException {
      //为了简单起见,所有的异常信息都往外抛
      int port = 8899;
      //定义一个ServerSocket监听在端口8899上
      ServerSocket server = new ServerSocket(port);
      //server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
      Socket socket = server.accept();
      //跟客户端建立好连接之后,我们就可以获取socket的InputStream,并从中读取客户端发过来的信息了。
      Reader reader = new InputStreamReader(socket.getInputStream());
      char chars[] = newchar[64];
      int len;
      StringBuilder sb = new StringBuilder();
      String temp;
      int index;
      while ((len=reader.read(chars)) != -1) {
         temp = new String(chars, 0, len);
         if ((index = temp.indexOf("eof")) != -1) {//遇到eof时就结束接收
            sb.append(temp.substring(0, index));
            break;
         }
         sb.append(temp);
      }
      System.out.println("from client: " + sb);
      //读完后写一句
      Writer writer = new OutputStreamWriter(socket.getOutputStream());
      writer.write("Hello Client.");
      writer.flush();
      writer.close();
      reader.close();
      socket.close();
      server.close();
   }
   
}

//客户端

public class Client {
 
   public static void main(String args[]) throws Exception {
      //为了简单起见,所有的异常都直接往外抛
     String host = "127.0.0.1";  //要连接的服务端IP地址
     int port = 8899;   //要连接的服务端对应的监听端口
     //与服务端建立连接
     Socket client = new Socket(host, port);
      //建立连接后就可以往服务端写数据了
     Writer writer = new OutputStreamWriter(client.getOutputStream());
      writer.write("Hello Server.");
      writer.flush();
      //写完以后进行读操作
     Reader reader = new InputStreamReader(client.getInputStream());
      char chars[] = newchar[64];
      int len;
      StringBuffer sb = new StringBuffer();
      while ((len=reader.read(chars)) != -1) {
         sb.append(new String(chars, 0, len));
      }
      System.out.println("from server: " + sb);
      writer.close();
      reader.close();
      client.close();
   }
   
}

多个客户端连接同一个服务端

 

public class Server {
   
   public static void main(String args[]) throws IOException {
      //为了简单起见,所有的异常信息都往外抛
     int port = 8899;
      //定义一个ServerSocket监听在端口8899上
     ServerSocket server = new ServerSocket(port);
      while (true) {
         //server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
         Socket socket = server.accept();
         //每接收到一个Socket就建立一个新的线程来处理它
         new Thread(new Task(socket)).start();
      }
   }
   
   /**
    * 用来处理Socket请求的
   */
   static class Task implements Runnable {
 
      private Socket socket;
      
      public Task(Socket socket) {
         this.socket = socket;
      }
      
      public void run() {

         try {

            handleSocket();
         } catch (Exception e) {
            e.printStackTrace();
         }
      }
      
      /**
       * 跟客户端Socket进行通信
       * @throws Exception
       */
      private void handleSocket() throws Exception {
         Reader reader = new InputStreamReader(socket.getInputStream());
         char chars[] = newchar[64];
         int len;
         StringBuilder sb = new StringBuilder();
         String temp;
         int index;
         while ((len=reader.read(chars)) != -1) {
            temp = new String(chars, 0, len);
            if ((index = temp.indexOf("eof")) != -1) {//遇到eof时就结束接收
             sb.append(temp.substring(0, index));
                break;
            }
            sb.append(temp);
         }
         System.out.println("from client: " + sb);
         //读完后写一句
       Writer writer = new OutputStreamWriter(socket.getOutputStream());
         writer.write("Hello Client.");
         writer.flush();
         writer.close();
         reader.close();
         socket.close();
      }
      
   }
   
}

 

 

posted on 2014-03-23 21:22  wjw334  阅读(222)  评论(0编辑  收藏  举报

导航