当前位置:网站首页>Communication layer of csframework
Communication layer of csframework
2022-07-04 10:28:00 【Lol only plays Timo】
From the beginning of this article, I will open a new pit for you , of java Some things of network programming in , Of course, I won't talk about some special basic things here , image socket,serversocket This kind of thing can be found on many websites , What I want to talk about is a framework , Based on this framework, we can develop something similar to chat room , The compilation of this framework can greatly improve everyone's understanding of java The ability to understand and code .
1. What is? C/S Pattern ?
The server - The client , namely Client-Server(C/S) structure .C/S The structure usually has two layers . The server is responsible for data management , The client is responsible for the interaction with the user .
2. How to layer ?
We said at the beginning that our goal is to develop something similar to chat room , that , The main task is the communication between users , And we are based on C/S pattern-developed , So I'm going to divide the framework we want to write into the following levels :
- The session layer ( Communication layer Communication): Sending of all messages , For example, the server sends messages to the client , Clients send messages to clients through this layer , And this session layer should be compatible with both server and client , Because the nature of sending messages is different .
- Server layer (Server): As the core part of the whole framework , He has the highest control over all clients , And the logic it needs to complete is very cumbersome , To achieve unified management of all clients .
- The client layer (Client): This layer is actually very abstract , Because what we write is just a framework , To put it bluntly, it's a tool. When we write it, we have no way to know the future APP The writers of the layer will make countermeasures for some responses of our clients , At this time, we should find another way , Find a convenient and simple way to walk , What exactly is it? I'll talk about it later .
Next is what we need to finish first , The most basic session layer ( Communication layer ):
For the conversation layer, we first need to know what we want to do , What functions should this session layer have for the upper layer ;
1. The first is the most important function – Send a message
2. Close the session layer
3. Start a listening thread , It mainly listens to messages sent and received from the opposite end
3. Official preparation
Sending information send Method
Let's get ready first , Since we communicate through the network, we definitely need one Socket Of , To send and receive messages, we need to prepare input and output communication channels , Here we transfer information through flow , therefore DataInputStream and DataOutputStream You should also be prepared , The switch of thread also needs a switch to facilitate our control, so we also need a boolean Variable of type
protected Socket socket;
protected DataInputStream dis;
protected DataOutputStream dos;
protected volatile boolean goon;
protected Communication(Socket socket) throws IOException {
this.socket = socket;
this.dis = new DataInputStream(this.socket.getInputStream());
this.dos = new DataOutputStream(this.socket.getOutputStream());
this.goon = true;
new Thread(this, "LOL Only play Timo ").start();
}
I believe careful students have found that boolean Type of goon A qualifier is added in front , The function of this qualifier is to frequently pair goon Prevent register optimization during operation .
After the preparatory work , Let's think about the first question , Send a message , This message contains a lot of content , If the type of message sent is generally defined as String Type words , It will definitely cause confusion , Because a message contains a lot of information , take “ single shot ” This operation is an example , It must be the client that tells the server I am a single shot operation , Who am I going to send it to , What message , In this case, a message contains three messages , Now let's see String As a type, it is indeed a very inappropriate practice , So we wrap this message in a class .
This class contains all the information contained in the message ( Take single shot as an example )<1> command command- single shot ,<2> action action- To whom ,<3> Real news message- What message . And the order is what we set , So we can define these commands with an enumeration .
public enum ENetCommand {
OUT_OF_ROOM,
ID,
OFFLINE,
FOREC_DOWN,
TO_ONE,
TO_OTHER,
TO_SP_OTHER,
REQUEST,
RESPONSE,
}
With this, we will improve the class used to encapsulate messages :
public class NetMessage {
private ENetCommand command;
private String message;
private String action;
public NetMessage() {
}
public ENetCommand getCommand() {
return command;
}
public NetMessage setCommand(ENetCommand command) {
this.command = command;
return this;
}
public String getMessage() {
return message;
}
public NetMessage setMessage(String message) {
this.message = message;
return this;
}
String getAction() {
return action;
}
NetMessage setAction(String action) {
this.action = action;
return this;
}
}
You can see all of me set The return value types of methods are NetMessage, Why is that ? If not, is it ok ?
First of all , If you don't do this, of course it's ok
second , In this way, we can pass new An anonymous object makes a chain call
The benefits of this writing can be seen in the next article .
So much preparation has been done for the news , We can simply write our sending method of sending messages :
protected void send(NetMessage netMessage) {
// Specify the message format , Avoid confusion
try {
this.dos.writeUTF(gson.toJson(netMessage));
} catch (IOException e) {
e.printStackTrace();
}
}
Why , Why will there be gson What about this thing ? It's because of our writeUTF The parameters of this method are String Type of , And the parameters we pass in are custom types , So we have to go through gson Convert our object into a standard format json character string , How to initialize this method – Please have a look at ->
public static final Gson gson = new GsonBuilder().create();
Using this requires a Gson A package , You can find it on the official website , You can also comment or send me a private message .
thus , We use it to send messages send This is the end of method writing .
Close the session layer
Closing operation actually seems to be relatively simple , Is to input the communication channel , Output communication channels and socket close , But if something goes wrong , Or can our program complete the closing operation normally when it is closed repeatedly ?
protected void close() {
this.goon = false;
try {
if (this.dis != null) {
this.dis.close();
}
} catch (IOException e) {
} finally {
this.dis =null;
}
try {
if (this.dos != null) {
this.dos.close();
}
} catch (IOException e) {
} finally {
this.dos = null;
}
try {
if (this.socket != null && !this.socket.isClosed()) {
this.socket.close();
}
} catch (IOException e) {
} finally {
this.socket = null;
}
}
In this, we will first control the continuous running of threads goon The assignment is false, Close the listening thread
And then test dis and dos Is there any for null, If null We won't do anything , If not for null If so, we will dis and dos close , You can see that I'm finally Lieutenant general dis and dos Assigned to null, In this way, even if there is an exception, our program can also dis and dos Make reasonable shutdown ,socket And the above dis and dos It's the same .
Start the listening thread , Listen for peer messages :
@Override
public void run() {
// The main function of thread is to listen for messages , And process the message
String message = "";
while(this.goon) {
try {
message = this.dis.readUTF();
dealNetMessage(gson.fromJson(message, NetMessage.class));
} catch (IOException e) {
// At this time IO The exception may be due to the end-to-end exception drop , No normal use close Method , therefore
// goon Not assigned to false
if (this.goon == true) {
this.goon = false;
peerAbnormalDrop();
}
}
}
}
The first is to read the sent information to , But don't forget that we passed on a Json character string , First convert it into a NetMessage Object of type , In order to correctly and reasonably analyze the transmitted information .
We can see that there are two functions that I have never mentioned :
dealNetMessage(); Functions and peerAbnormalDrop(); function
Why am I here communication It's not mentioned in the layer ? Because these two functions are not what I am communication What should be done in the layer !
dealNetMessage(); It refers to how to handle the sent message , We are communication Layer only does the most basic communication work , As for how to deal with messages, it should be done by the session layer ;peerAbnormalDrop(); It refers to the abnormal disconnection of the opposite end , This should also be handled in the session layer, and it is not us communication What the layer should do . But the current logic does need these two things , What shall I do? —— Abstract method !!!
Define these two functions as abstract methods APP We only need to implement these two methods to write the layer , In this way, the whole logic is complete , This is the role of abstract methods !
This is the end of the basic session layer of this chapter , The subsequent preparation of the server and client will be updated soon , If someone thinks I'm not writing correctly , Welcome criticism and correction !
Finally, the source code is attached , For reference only :
public abstract class Communication implements Runnable{
public static final Gson gson = new GsonBuilder().create();
protected Socket socket;
protected DataInputStream dis;
protected DataOutputStream dos;
protected volatile boolean goon;
protected Communication(Socket socket) throws IOException {
this.socket = socket;
this.dis = new DataInputStream(this.socket.getInputStream());
this.dos = new DataOutputStream(this.socket.getOutputStream());
this.goon = true;
new Thread(this, "LOL Only play Timo ").start();
}
public abstract void dealNetMessage(NetMessage netMessage);
public abstract void peerAbnormalDrop();
protected void send(NetMessage netMessage) {
// Specify the message format , Avoid confusion
try {
this.dos.writeUTF(gson.toJson(netMessage));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
// The main function of thread is to listen for messages , And process the message
String message = "";
while(this.goon) {
try {
message = this.dis.readUTF();
dealNetMessage(gson.fromJson(message, NetMessage.class));
} catch (IOException e) {
// At this time IO The exception may be due to the end-to-end exception drop , No normal use close Method , therefore
// goon Not assigned to false
if (this.goon == true) {
this.goon = false;
peerAbnormalDrop();
}
}
}
}
public void close() {
this.goon = false;
if (dis != null) {
try {
this.dis.close();
} catch (IOException e) {
} finally {
this.dis = null;
}
}
if (dos != null) {
try {
this.dos.close();
} catch (IOException e) {
} finally {
this.dos = null;
}
}
if (this.socket != null && !this.socket.isClosed()) {
try {
this.socket.close();
} catch (IOException e) {
} finally {
this.socket = null;
}
}
}
}
边栏推荐
- View CSDN personal resource download details
- 基于线性函数近似的安全强化学习 Safe RL with Linear Function Approximation 翻译 1
- Dynamic memory management
- Exercise 7-2 finding the maximum value and its subscript (20 points)
- Exercise 7-3 store the numbers in the array in reverse order (20 points)
- Exercise 7-8 converting strings to decimal integers (15 points)
- Sword finger offer 05 (implemented in C language)
- Check 15 developer tools of Alibaba
- Crawl Zhejiang industry and trade news page
- The bamboo shadow sweeps the steps, the dust does not move, and the moon passes through the marsh without trace -- in-depth understanding of the pointer
猜你喜欢
The bamboo shadow sweeps the steps, the dust does not move, and the moon passes through the marsh without trace -- in-depth understanding of the pointer
Application of safety monitoring in zhizhilu Denggan reservoir area
OSPF summary
A little feeling
Delayed message center design
Three schemes of ZK double machine room
【Day2】 convolutional-neural-networks
Four characteristics and isolation levels of database transactions
From programmers to large-scale distributed architects, where are you (2)
2. Data type
随机推荐
uniapp 处理过去时间对比现在时间的时间差 如刚刚、几分钟前,几小时前,几个月前
Dynamic memory management
Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?
PHP代码审计3—系统重装漏洞
Batch distribution of SSH keys and batch execution of ansible
Time complexity and space complexity
2. Data type
Map container
Button wizard business running learning - commodity quantity, price reminder, judgment Backpack
/*Write a function to open the file for input, read the contents of the file into the vector container of string class 8.9: type, and store each line as an element of the container object*/
Differences among opencv versions
OSPF summary
IPv6 comprehensive experiment
What is devsecops? Definitions, processes, frameworks and best practices for 2022
Leetcode48. Rotate image
How to teach yourself to learn programming
Some summaries of the third anniversary of joining Ping An in China
DDL statement of MySQL Foundation
Es entry series - 6 document relevance and sorting
Exercise 8-10 output student grades (20 points)