当前位置:网站首页>Instant messaging and BS architecture simulation of TCP practical cases
Instant messaging and BS architecture simulation of TCP practical cases
2022-06-28 09:46:00 【Yu an one hundred and twelve】
What does instant messaging mean , What kind of design should be implemented ?
1、 Instant messaging , It refers to the message sent by a client , Other clients can receive
2、 Before, our messages were sent to the server
3、 Instant messaging needs the design idea of port forwarding
4、 The server needs to put online Socket Pipe storage
5、 Once you receive a message, push it to other channels
client :
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TCP_ Practical cases _ Instant messaging {
public static void main(String[] args) throws Exception {
System.out.println("----- The client starts -----");
// establish Socket The communication pipeline requests a connection to the server
/*
public Socket(String host, int port)
Parameter one 、 Server's IP Address
Parameter two 、 The port of the server
*/
Socket socket = new Socket("127.0.0.1", 7777);
// Create a separate thread to be responsible for the client's message reading ( The server may forward at any time !)
new ClientReaderThread(socket).start();
// from Socket Get a byte output stream from the communication pipeline , Responsible for sending data
OutputStream out = socket.getOutputStream();
// Wrap the low-level byte stream into a print stream
PrintStream ps = new PrintStream(out);
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println(" Please enter the message you want to send :");
String line = sc.nextLine();
// Send a message
ps.println(line);
// Refresh
ps.flush();
}
}
}
// Client read message thread
class ClientReaderThread extends Thread{
private Socket socket;
public ClientReaderThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
// from Socket Get a byte input stream in the communication pipeline
InputStream is = socket.getInputStream();
// The byte input stream is wrapped into a buffered byte input stream to receive messages
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Read the message by line
String line;
while ((line = br.readLine()) != null) {
System.out.println(" Received a message :" + line);
}
} catch (Exception e) {
System.out.println( " The server has kicked you out !");
}
}
}
Server side :
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class TCP_ Instant messaging _ Server side {
// Define a static List Collections store all currently online socket The Conduit
public static List<Socket> allonlineSockets=new ArrayList<>();
public static void main(String[] args) throws Exception {
System.out.println("----- Server startup -----");
// Registered port
ServerSocket serverSocket = new ServerSocket(7777);
// Define an endless loop in which the main thread is responsible for continuously receiving the data from the client Socket Communication pipeline connection
while (true) {
// Every time a client receives Socket Communication pipeline , Give it to an independent sub thread to read the information
Socket socket = serverSocket.accept();
System.out.println(socket.getRemoteSocketAddress() + " launched ");
allonlineSockets.add(socket);// Online completion
// Create a separate thread to handle this socket The Conduit
new ServerReaderThread(socket).start();
}
}
}
class ServerReaderThread extends Thread {
private Socket socket;
public ServerReaderThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
// from Socket Get a byte input stream in the communication pipeline
InputStream is = socket.getInputStream();
// The byte input stream is wrapped into a buffered byte input stream to receive messages
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Read the message by line
String line;
while ((line = br.readLine()) != null) {
System.out.println(" Received the message :" + line);
// Port forward this message to all clients socket The Conduit
sendMsgToAll(line);
}
} catch (Exception e) {
System.out.println(socket.getRemoteSocketAddress() + " Get offline ");
TCP_ Instant messaging _ Server side .allonlineSockets.remove(socket);// Delete
}
}
// Independent functions are independent methods
private void sendMsgToAll(String msg) throws Exception {
for (Socket socket : TCP_ Instant messaging _ Server side .allonlineSockets) {
PrintStream ps=new PrintStream(socket.getOutputStream());
ps.println(msg);
ps.flush();
}
}
}
Running effect :
There is a flaw here, that is, the messages sent do not shield themselves , The two are the same because concurrency is enabled .
The following is the effect of closing the server :
BS Architecture simulation :
1、 What were the previous clients like ?
In fact, that is CS framework , The client needs to be developed and implemented by ourselves .
2、BS What is the structure , Need to develop client ?
Browser access server , No client development required .
Simple simulation :
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;
public class TCP_BS framework {
public static void main(String[] args) throws Exception {
// Registered port
ServerSocket serverSocket = new ServerSocket(7070);
// Define an endless loop in which the main thread is responsible for continuously receiving the data from the client Socket Communication pipeline connection
while (true) {
// Every time a client receives Socket Communication pipeline , Give it to an independent sub thread to read the information
Socket socket = serverSocket.accept();
// Create a separate thread to handle this socket The Conduit
new ServerReaderThread2(socket).start();
}
}
}
class ServerReaderThread2 extends Thread {
private Socket socket;
public ServerReaderThread2(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// The browser has been established with this thread socket The Conduit
// The response message is displayed to the browser
try {
PrintStream ps=new PrintStream(socket.getOutputStream());
// Must respond to HTTP Protocol format data , Otherwise, the browser does not recognize the message
ps.println("HTTP/1.1 200 OK");// Protocol type and version Respond to a successful message
ps.println("Content-Type:text/html;charset=UTF-8");// The data type of the response : Text / Webpage
ps.println();// A space must be sent
// Then you can respond to the data and go back to the browser
ps.println("<span style='color:red;font-size:90px'>《 Yu an .》 </span>");
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thread pool optimization :
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;
public class TCP_BS framework {
private static ExecutorService pools = new ThreadPoolExecutor(3, 5,
6, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) throws Exception {
// Registered port
ServerSocket serverSocket = new ServerSocket(7070);
// Define an endless loop in which the main thread is responsible for continuously receiving the data from the client Socket Communication pipeline connection
while (true) {
// Every time a client receives Socket Communication pipeline , Give it to an independent sub thread to read the information
Socket socket = serverSocket.accept();
pools.execute(new ServerRunnable2(socket));
}
}
}
class ServerRunnable2 implements Runnable {
private Socket socket;
public ServerRunnable2(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// The browser has been established with this thread socket The Conduit
// The response message is displayed to the browser
try {
PrintStream ps=new PrintStream(socket.getOutputStream());
// Must respond to HTTP Protocol format data , Otherwise, the browser does not recognize the message
ps.println("HTTP/1.1 200 OK");// Protocol type and version Respond to a successful message
ps.println("Content-Type:text/html;charset=UTF-8");// The data type of the response : Text / Webpage
ps.println();// A space must be sent
// Then you can respond to the data and go back to the browser
ps.println("<span style='color:red;font-size:90px'>《 Yu an .》 </span>");
ps.close();
} catch (Exception e) {
System.out.println(socket.getRemoteSocketAddress() + " Get offline ");
}
}
}
In the browser rendering :
边栏推荐
猜你喜欢
HDI的盲孔设计,你注意到这个细节了吗?
Linux下安装redis 、Windows下安装redis(超详细图文教程)
TCP实战案例之即时通信、BS架构模拟
A classic JVM class loaded interview question class singleton{static singleton instance = new singleton(); private singleton() {}
Dbeaver连接人大金仓KingbaseES V8(超详细图文教程)
QT signal and slot communication mechanism (when multiple windows communicate back and forth [parent and child windows])
new URL(“www.jjj.com“)
线程的生命周期
组合模式(Composite Pattern)
The concept of "tree structure" perfectly interprets the primary and secondary of things
随机推荐
Key summary IV of PMP examination - planning process group (2)
2020-10-27
Linux下安装redis 、Windows下安装redis(超详细图文教程)
1181:整数奇偶排序
A classic JVM class loaded interview question class singleton{static singleton instance = new singleton(); private singleton() {}
Restful style
纵观jBPM从jBPM3到jBPM5以及Activiti
组合模式(Composite Pattern)
Differences between task parameter types inout and ref
When the interviewer asks you to write binarysort in two ways
栈的弹出压入序列<难度系数>
PMP examination key summary VIII - monitoring process group (2)
异常
June 27, 2022: give a 01 string with a length of N. now please find two intervals so that the number of 1 is equal and the number of 0 is equal in the two intervals. The two intervals can intersect bu
Summary of PMP learning experience
1180: fractional line delimitation /p1068 [noip2009 popularization group] fractional line delimitation
Divide and rule classic Hanoi
JVM系列(2)——垃圾回收
[ybtoj advanced training guide] maximum separation [hash] [Floyd]
适配器模式(Adapter)