Home  >  Article  >  Java  >  Java Socket Programming

Java Socket Programming

高洛峰
高洛峰Original
2016-12-13 10:02:231318browse

For Java Socket programming, there are two concepts, one is ServerSocket and the other is Socket. A connection is established between the server and the client through Socket, and then they can communicate. First, ServerSocket will listen to a certain port on the server side. When it finds that the client has a Socket and tries to connect to it, it will accept the connection request of the Socket and establish a corresponding Socket on the server side to communicate with it. In this way, there are two Sockets, one for the client and one for the server.

           Communication between Sockets is actually very simple. The server writes something into the Socket’s output stream, and the client can read the corresponding content through the Socket’s input stream. There is a two-way connection between Socket and Socket, so the client can also write things into the corresponding Socket output stream, and then the corresponding Socket input stream on the server can read the corresponding content. Let’s look at some examples of communication between the server and the client:

1. The client writes and the server reads

Server code

Java code

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[] = new char[64];  
      int len;  
      StringBuilder sb = new StringBuilder();  
      while ((len=reader.read(chars)) != -1) {  
         sb.append(new String(chars, 0, len));  
      }  
      System.out.println("from client: " + sb);  
      reader.close();  
      socket.close();  
      server.close();  
   }  
     
}

The server also reads data from the InputStream of the Socket. Blocking, if no data is read from the input stream, the program will remain there until the client writes data to the Socket's output stream or closes the Socket's output stream. Of course, the same is true for the client's Socket. After the operation is completed, remember to close the corresponding resources before the entire program ends, that is, close the corresponding IO stream and Socket.

                                                                                  use   with                                 out out out out out out out out out out right outallowce outOUT out out outOUT out out out out out out's be ’s ’’s’’’ through out’s' through out’s‐’‐out‐out‐out-stream bearer have bets on client code

For blocking operations (such as reading data from the input stream), remember to flush. Only in this way can the server receive the data sent by the client, otherwise it may cause both parties to wait for each other indefinitely. This issue will be discussed later when the client and server read and write at the same time.

2. The client and server read and write at the same time

As mentioned before, Socket is a two-way communication. It can receive data and send data at the same time.

Service side code

Java code

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();//写完后要记得flush  
      writer.close();  
      client.close();  
   }  
     
}

In the above code, we first read the data sent by the client from the input stream. Close the corresponding resource file. In fact, the above code may not run as we expected, because reading data from the input stream is a blocking operation. In the above while loop, the loop body will be executed when the data is read, otherwise It will block, so that subsequent write operations will never be executed. The blocking will not stop unless the corresponding Socket of the client is closed, and the while loop will also jump out. The solution to this situation that may never be executed is that the while loop needs to conditionally jump out of it. Looking at the above code, the only things that are constantly changing are the fetched length len and the read data. len has already It can no longer be used. The only thing that can be used is the data read. In response to this situation, we usually agree on an end tag. When the data sent by the client contains an end tag, it means that the current data has been sent. At this time, we can jump out of the loop. Then the improved code will look like this:

Java code

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[] = new char[64];  
      int len;  
      StringBuilder sb = new StringBuilder();  
      while ((len=reader.read(chars)) != -1) {  
         sb.append(new String(chars, 0, len));  
      }  
      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();  
   }  
     
}

In the above code, when the server reads the end tag sent by the client, that is, "eof", it will end the reception of data and terminate the loop. In this way, subsequent code can continue.代The client code

Java code

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[] = new char[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();  
   }  
     
}

We first sent a data to the server in the above code, and then read the data returned from the server. As a result, the program always hangs there and can never get out of the while loop. This code, combined with the first piece of code on the server, allows us to analyze that the server will always receive data there, and will never get out of the while loop. Therefore, there will be no subsequent data returned by the server to the client, and it will be impossible for the client to receive it. Data returned to the server. The solution is as shown in the second piece of code on the server side. After the client completes sending the data, write an end tag into the output stream to tell the server that the data has been sent. Similarly, after the server completes returning the data, it also sends a tag to tell the client. end. Then the modified client code should look like this:

Java code

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.write("eof");  
      writer.flush();  
      //写完以后进行读操作  
     Reader reader = new InputStreamReader(client.getInputStream());  
      char chars[] = new char[64];  
      int len;  
      StringBuffer sb = new StringBuffer();  
      String temp;  
      int index;  
      while ((len=reader.read(chars)) != -1) {  
         temp = new String(chars, 0, len);  
         if ((index = temp.indexOf("eof")) != -1) {  
            sb.append(temp.substring(0, index));  
            break;  
         }  
         sb.append(new String(chars, 0, len));  
      }  
      System.out.println("from server: " + sb);  
      writer.close();  
      reader.close();  
      client.close();  
   }  
     
}

我们日常使用的比较多的都是这种客户端发送数据给服务端,服务端接收数据后再返回相应的结果给客户端这种形式。只是客户端和服务端之间不再是这种一对一的关系,而是下面要讲到的多个客户端对应同一个服务端的情况。

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

       像前面讲的两个例子都是服务端接收一个客户端的请求之后就结束了,不能再接收其他客户端的请求了,这往往是不能满足我们的要求的。通常我们会这样做:

Java代码 

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的InputStream,并从中读取客户端发过来的信息了。  
       Reader reader = new InputStreamReader(socket.getInputStream());  
         char chars[] = new char[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();  
      }  
   }  
     
}

在上面代码中我们用了一个死循环,在循环体里面ServerSocket调用其accept方法试图接收来自客户端的连接请求。当没有接收到请求的时候,程序会在这里阻塞直到接收到来自客户端的连接请求,之后会跟当前建立好连接的客户端进行通信,完了后会接着执行循环体再次尝试接收新的连接请求。这样我们的ServerSocket就能接收来自所有客户端的连接请求了,并且与它们进行通信了。这就实现了一个简单的一个服务端与多个客户端进行通信的模式。

       上述例子中虽然实现了一个服务端跟多个客户端进行通信,但是还存在一个问题。在上述例子中,我们的服务端处理客户端的连接请求是同步进行的,每次接收到来自客户端的连接请求后,都要先跟当前的客户端通信完之后才能再处理下一个连接请求。这在并发比较多的情况下会严重影响程序的性能,为此,我们可以把它改为如下这种异步处理与客户端通信的方式:

Java代码 

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[] = new char[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();  
      }  
        
   }  
     
}

在上面代码中,每次ServerSocket接收到一个新的Socket连接请求后都会新起一个线程来跟当前Socket进行通信,这样就达到了异步处理与客户端Socket进行通信的情况。

       在从Socket的InputStream中接收数据时,像上面那样一点点的读就太复杂了,有时候我们就会换成使用BufferedReader来一次读一行,如:

Java代码 

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 {  
         BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
         StringBuilder sb = new StringBuilder();  
         String temp;  
         int index;  
         while ((temp=br.readLine()) != null) {  
            System.out.println(temp);  
            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.write("eof\n");  
         writer.flush();  
         writer.close();  
         br.close();  
         socket.close();  
      }  
   }  
}

这个时候需要注意的是,BufferedReader的readLine方法是一次读一行的,这个方法是阻塞的,直到它读到了一行数据为止程序才会继续往下执行,那么readLine什么时候才会读到一行呢?直到程序遇到了换行符或者是对应流的结束符readLine方法才会认为读到了一行,才会结束其阻塞,让程序继续往下执行。所以我们在使用BufferedReader的readLine读取数据的时候一定要记得在对应的输出流里面一定要写入换行符(流结束之后会自动标记为结束,readLine可以识别),写入换行符之后一定记得如果输出流不是马上关闭的情况下记得flush一下,这样数据才会真正的从缓冲区里面写入。对应上面的代码我们的客户端程序应该这样写:

Java代码 

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.write("eof\n");  
      writer.flush();  
      //写完以后进行读操作  
     BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));  
      StringBuffer sb = new StringBuffer();  
      String temp;  
      int index;  
      while ((temp=br.readLine()) != null) {  
         if ((index = temp.indexOf("eof")) != -1) {  
            sb.append(temp.substring(0, index));  
            break;  
         }  
         sb.append(temp);  
      }  
      System.out.println("from server: " + sb);  
      writer.close();  
      br.close();  
      client.close();  
   }  
}

      4、设置超时时间

       假设有这样一种需求,我们的客户端需要通过Socket从服务端获取到XX信息,然后给用户展示在页面上。我们知道Socket在读数据的时候是阻塞式的,如果没有读到数据程序会一直阻塞在那里。在同步请求的时候我们肯定是不能允许这样的情况发生的,这就需要我们在请求达到一定的时间后控制阻塞的中断,让程序得以继续运行。Socket为我们提供了一个setSoTimeout()方法来设置接收数据的超时时间,单位是毫秒。当设置的超时时间大于0,并且超过了这一时间Socket还没有接收到返回的数据的话,Socket就会抛出一个SocketTimeoutException。

       假设我们需要控制我们的客户端在开始读取数据10秒后还没有读到数据就中断阻塞的话我们可以这样做:

 

Java代码 

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.write("eof\n");  
      writer.flush();  
      //写完以后进行读操作  
     BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));  
      //设置超时间为10秒  
     client.setSoTimeout(10*1000);  
      StringBuffer sb = new StringBuffer();  
      String temp;  
      int index;  
      try {  
         while ((temp=br.readLine()) != null) {  
            if ((index = temp.indexOf("eof")) != -1) {  
                sb.append(temp.substring(0, index));  
                break;  
            }  
            sb.append(temp);  
         }  
      } catch (SocketTimeoutException e) {  
         System.out.println("数据读取超时。");  
      }  
      System.out.println("from server: " + sb);  
      writer.close();  
      br.close();  
      client.close();  
   }  
}

      5、接收数据乱码

       对于这种服务端或客户端接收中文乱码的情况通常是因为数据发送时使用的编码跟接收时候使用的编码不一致。比如有下面这样一段服务端代码:

Java代码 

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 {  
         BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));  
         StringBuilder sb = new StringBuilder();  
         String temp;  
         int index;  
         while ((temp=br.readLine()) != null) {  
            System.out.println(temp);  
            if ((index = temp.indexOf("eof")) != -1) {//遇到eof时就结束接收  
             sb.append(temp.substring(0, index));  
                break;  
            }  
            sb.append(temp);  
         }  
         System.out.println("客户端: " + sb);  
         //读完后写一句  
       Writer writer = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");  
         writer.write("你好,客户端。");  
         writer.write("eof\n");  
         writer.flush();  
         writer.close();  
         br.close();  
         socket.close();  
      }  
   }  
}

这里用来测试我就弄的混乱了一点。在上面服务端代码中我们在定义输入流的时候明确定义了使用GBK编码来读取数据,而在定义输出流的时候明确指定了将使用UTF-8编码来发送数据。如果客户端上送数据的时候不以GBK编码来发送的话服务端接收的数据就很有可能会乱码;同样如果客户端接收数据的时候不以服务端发送数据的编码,即UTF-8编码来接收数据的话也极有可能会出现数据乱码的情况。所以,对于上述服务端代码,为使我们的程序能够读取对方发送过来的数据,而不出现乱码情况,我们的客户端应该是这样的:

Java代码 

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(), "GBK");  
      writer.write("你好,服务端。");  
      writer.write("eof\n");  
      writer.flush();  
      //写完以后进行读操作  
     BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));  
      //设置超时间为10秒  
     client.setSoTimeout(10*1000);  
      StringBuffer sb = new StringBuffer();  
      String temp;  
      int index;  
      try {  
         while ((temp=br.readLine()) != null) {  
            if ((index = temp.indexOf("eof")) != -1) {  
                sb.append(temp.substring(0, index));  
                break;  
            }  
            sb.append(temp);  
         }  
      } catch (SocketTimeoutException e) {  
         System.out.println("数据读取超时。");  
      }  
      System.out.println("服务端: " + sb);  
      writer.close();  
      br.close();  
      client.close();  
   }  
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn