Home > Java > javaTutorial > body text

Some experiences on Java network programming

零下一度
Release: 2017-07-17 13:11:59
Original
2495 people have browsed it

Recently I have been learning Java network programming. I have heard of it before, but I have never understood it seriously. In the past few days, I suddenly became interested and felt that it was very magical. I suddenly wanted to know what the specific situation was.

Socket is usually called "socket", which is used to describe the IP address and port. It is a handle of a communication chain. Hosts on the Internet generally run multiple service software and provide several services at the same time. Each service opens a Socket and is bound to a port. Different ports correspond to different services.


Socket is very similar to a telephone socket. Taking a national telephone network as an example, the two parties on the phone call are equivalent to two processes communicating with each other, and the area code is its network address; a switch in a unit in the area is equivalent to a host, and the host assigns an intra-office number to each user. Equivalent to Socket number. Before any user makes a call, he must first possess a telephone, which is equivalent to applying for a Socket; at the same time, he must know the other party's number, which is equivalent to the other party having a fixed Socket. Then dial a call to the other party, which is equivalent to issuing a connection request (if the other party is not in the same area, you also need to dial the other party's area code, which is equivalent to giving a network address). If the other party is present and idle (equivalent to the other communication host being turned on and able to accept connection requests), pick up the phone receiver, and the two parties can officially talk, which is equivalent to a successful connection. The process of a call between the two parties is the process of one party sending a signal to the phone and the other party receiving the signal from the phone, which is equivalent to sending data to the Socket and receiving data from the Socket. After the call ends, one party hanging up the phone is equivalent to closing the Socket and canceling the connection.


In the telephone system, the average user can only feel the existence of the local telephone and the other party's phone number. The process of establishing a call, the process of voice transmission and the technical details of the entire telephone system are all to him. Transparent, this is also very similar to the Socket mechanism. Socket uses Internet communication facilities to achieve process communication, but it does not care about the details of the communication facilities. As long as the communication facilities can provide sufficient communication capabilities, it is satisfied.
These are the definitions and explanations in Baidu Encyclopedia, but they are quite easy to understand, unlike the previous explanations which were not easy to understand. There were too many professional terms and it was very difficult to understand.


Socket communication implementation steps:
1. Create ServerSocket and Socket
2. Open the input/output stream to connect to the Socket 3. Follow the protocol (usually TCP/UDP) Read and write operations on Socket
4. Close the input/output stream and close Socket

Socket programming

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.

The communication between Sockets is actually very simple. The server writes things into the output stream of the Socket, and the client can read the corresponding content through the input stream of the Socket. 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.

Some experiences on Java network programming

The following is an example, client read and write and server read and write

Server code

public class Server {
public static void main(String args[]) throws IOException {
      //定义一个ServerSocket监听在端口8888上  
      int port = 8888; 
      int i=1; //连接计数
      //server尝试接收其他Socket的连接请求,
      ServerSocket server = new ServerSocket(port);  
      //server的accept方法是阻塞式的 ,即等待着客户端的请求
      Socket socket = server.accept();  
      System.out.println("连接"+i++);
      //跟客户端建立好连接,我们就可以获取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(); 
   }  
}
Copy after login

Output

Some experiences on Java network programming

Note

  • The operation of the server to read data from the InputStream of the Socket is also blocking. If no data is read from the input stream, the program It 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.

  • Read the data sent by the client from the input stream, then we write the data to the output stream to the client, and then 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 will block, so that subsequent write operations will never be executed. For this situation, we usually agree on an end mark. When the data sent by the client contains an end mark, it means that the current data has been sent. , at this time we can jump out of the loop.

  • 在上述代码中,当服务端读取到客户端发送的结束标记,即“eof”时就会结束数据的接收,终止循环,这样后续的代码又可以继续进行了。

客户端代码

public class Client {
 public static void main(String args[]) throws Exception {  
      //为了简单起见,所有的异常都直接往外抛  
      String host = "192.168.74.1";  //要连接的服务端IP地址  
      int port = 8888;   //要连接的服务端对应的监听端口  
      //与服务端建立连接  
      Socket client = new Socket(host, port);  
      //建立连接后就可以往服务端写数据了  
      Writer writer = new OutputStreamWriter(client.getOutputStream());  
      writer.write("Hello ,我是客户端输入数据");
      writer.write("eof"); 
      writer.flush();//写完后要记得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();  
   }  
}
Copy after login

输出

Some experiences on Java network programming

注意点

  • 过程:先是给服务端发送了一段数据,之后读取服务端返回来的数据,跟之前的服务端一样在读的过程中有可能导致程序一直挂在那里,永远跳不出while循环,解决方法和服务端一样,用一个结束标志。

  • 对于客户端往Socket的输出流里面写数据传递给服务端要注意一点,如果写操作之后程序不是对应着输出流的关闭,而是进行其他阻塞式的操作(比如从输入流里面读数据),记住要flush一下,只有这样服务端才能收到客户端发送的数据,否则可能会引起两边无限的互相等待。在稍后讲到客户端和服务端同时读和写的时候会说到这个问题。

The above is the detailed content of Some experiences on Java network programming. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template