Some experiences on Java network programming
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
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.
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
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(); } }
- 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(); } }
输出
注意点
过程:先是给服务端发送了一段数据,之后读取服务端返回来的数据,跟之前的服务端一样在读的过程中有可能导致程序一直挂在那里,永远跳不出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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is
