futurejava前台_web前端页面与后端Java的数据交互
java代碼:
package com.lpc.main;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/**
* ?* 類名稱:Server.java 類描述:簡單的聊天室 作 者:wantao 時(shí) 間:2018年03月08日 23:11:48
*/
@ServerEndpoint(value = "/chat")
public class Test {
private static final String GUEST_PREFIX = "用戶";
/**
* 一個(gè)提供原子操作的Integer的類。在Java語言中,++i和i++操作并不是線程安全的,
* 在使用的時(shí)候,不可避免的會(huì)用到synchronized關(guān)鍵字。 而AtomicInteger則通過一種線程安全的加減操作接口。
*/
private static final AtomicInteger connectionIds = new AtomicInteger(0);
// 存放用戶的websocket
private static final Set connections = new CopyOnWriteArraySet<>();
private final String nickname;
private Session session;
public Test() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
/**
* 創(chuàng)建連接時(shí)間調(diào)用的方法
*
* @param session
*/
@OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "加入聊天室");
// 上線通知
broadcast(message);
try {
// 系統(tǒng)問候語
SendHello(this.nickname);
// 返回在線用戶
onlineList();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 鏈接關(guān)閉時(shí)調(diào)用方法
*/
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s", nickname, "退出聊天室");
broadcast(message);
}
/**
* 傳輸信息過程中調(diào)用方法
*
* @param message
*/
@OnMessage
public void incoming(String message) {
// Never trust the client
// TODO: 過濾輸入的內(nèi)容
String m = String.format("* %s %s", nickname, message);
if (m.contains("to")) {
// 點(diǎn)對點(diǎn)發(fā)送
broadcastOneToOne(m, nickname);
} else {
// 群發(fā)
broadcast(m);
}
}
/**
* 發(fā)生錯(cuò)誤是調(diào)用方法
*
* @param t
* @throws Throwable
*/
@OnError
public void onError(Throwable t) throws Throwable {
System.out.println("錯(cuò)誤: " + t.toString());
}
/**
* 消息廣播 通過connections,對所有其他用戶推送信息的方法
*
* @param msg
*/
private static void broadcast(String msg) {
for (Test client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
System.out.println("錯(cuò)誤:向客戶端發(fā)送消息失敗");
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String message = String.format("* %s %s", client.nickname,
"退出聊天室");
broadcast(message);
}
}
}
/**
* 點(diǎn)對點(diǎn)發(fā)送消息 通過connections,對所有其他用戶推送信息的方法
*
* @param msg
*/
private static void broadcastOneToOne(String msg, String nickName) {
String[] arr = msg.split("to");
for (Test client : connections) {
try {
if (arr[1].equals(client.nickname)
|| nickName.equals(client.nickname)) {
synchronized (client) {
client.session.getBasicRemote().sendText(arr[0]);
}
}
} catch (IOException e) {
System.out.println("錯(cuò)誤:向客戶端發(fā)送消息失敗");
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String message = String.format("* %s %s", client.nickname,
"退出聊天室");
broadcast(message);
}
}
}
// 系統(tǒng)問候語
private static void SendHello(String nickName) throws IOException {
String m = String.format("* %s %s", nickName, "你好");
for (Test client : connections) {
if (client.nickname.equals(nickName)) {
client.session.getBasicRemote().sendText(m);
}
}
}
// 在線用戶
private static void onlineList() throws IOException {
String online = "";
for (Test client : connections) {
if (online.equals("")) {
online = client.nickname;
} else {
online += "," + client.nickname;
}
}
String m = String.format("* %s %s", "當(dāng)前在線用戶", online);
for (Test client : connections) {
client.session.getBasicRemote().sendText(m);
}
}
}
jsp文件
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
websocketinput#chat {
width: 410px
}
#console-container {
width: 400px;
}
#console {
border: 1px solid #CCCCCC;
border-right-color: #999999;
border-bottom-color: #999999;
height: 170px;
overflow-y: scroll;
padding: 5px;
width: 100%;
}
#console p {
padding: 0;
margin: 0;
}
"use strict";
var Chat = {};
Chat.socket = null;
Chat.connect = (function(host) {
if ('WebSocket' in window) {
Chat.socket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
Chat.socket = new MozWebSocket(host);
} else {
Console.log('Error: 瀏覽器不支持WebSocket');
return;
}
Chat.socket.onopen = function () {
Console.log('Info: WebSocket鏈接已打開');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
Chat.sendMessage();
}
};
};
Chat.socket.onclose = function () {
document.getElementById('chat').onkeydown = null;
Console.log('Info: webcocket關(guān)閉.');
};
Chat.socket.onmessage = function (message) {
Console.log(message.data);
};
});
Chat.initialize = function() {
if (window.location.protocol == 'http:') {
Chat.connect('ws://' + window.location.host + '/WebSocket/chat');
} else {
Chat.connect('wss://' + window.location.host + '/WebSocket/chat');
}
};
Chat.sendMessage = (function() {
var message = document.getElementById('chat').value;
if (message != '') {
Chat.socket.send(message);
document.getElementById('chat').value = '';
}
});
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
Chat.initialize();
document.addEventListener("DOMContentLoaded", function() {
// Remove elements with "noscript" class -
is not allowed in XHTMLvar noscripts = document.getElementsByClassName("noscript");
for (var i = 0; i < noscripts.length; i++) {
noscripts[i].parentNode.removeChild(noscripts[i]);
}
}, false);
Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
Javascript and reload this page!
注意:輸入? 消息to用戶名? ?發(fā)送給指定用戶? ?比如:? 你好to用戶1
輸入? ?消息? ? ?直接發(fā)送給全體用戶
運(yùn)行后提示
Info: webcocket關(guān)閉.
eclipse控制臺(tái)輸出信息:
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server.服務(wù)器版本: Apache Tomcat/9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server.構(gòu)建: Mar 13 2019 15:55:27 UTC
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server version number: 9.0.17.0
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS Name: Windows 10
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS.版本: 10.0
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: 結(jié).造: amd64
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Java 環(huán)境變量: C:\Program Files\Java\jdk-11.0.2
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM 版本: 11.0.2+9-LTS
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM.供應(yīng)商: Oracle Corporation
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_BASE: D:\workspace\eclipse-web\apache-tomcat-9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_HOME: D:\workspace\eclipse-web\apache-tomcat-9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.base=D:\workspace\eclipse-web\apache-tomcat-9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.home=D:\workspace\eclipse-web\apache-tomcat-9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dwtp.deploy=D:\workspace\eclipse-web\apache-tomcat-9.0.17\wtpwebapps
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dfile.encoding=GBK
4月 15, 2019 9:30:31 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk-11.0.2\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jdk-11.0.2/bin/server;C:/Program Files/Java/jdk-11.0.2/bin;C:\Program Files\Java\jdk-11.0.2\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\dotnet\;C:\Program Files\MySQL\MySQL Server 8.0\bin;C:\Program Files\MATLAB\R2016a\runtime\win64;C:\Program Files\MATLAB\R2016a\bin;C:\Program Files\MATLAB\R2016a\polyspace\bin;C:\Program Files\Git\cmd;C:\Program Files\apache-maven-3.6.0\bin;C:\MinGW\bin;C:\Users\xupt1602\AppData\Local\Microsoft\WindowsApps;C:\Users\xupt1602\.dotnet\tools;C:\Users\xupt1602\AppData\Local\GitHubDesktop\bin;;C:\WINDOWS\system32;;.]
4月 15, 2019 9:30:31 下午 org.apache.coyote.AbstractProtocol init
信息: 初始化協(xié)議處理器 ["http-nio-8080"]
4月 15, 2019 9:30:32 下午 org.apache.coyote.AbstractProtocol init
信息: 初始化協(xié)議處理器 ["ajp-nio-8009"]
4月 15, 2019 9:30:32 下午 org.apache.catalina.startup.Catalina load
信息: 服務(wù)器在[2,091]毫秒內(nèi)初始化
4月 15, 2019 9:30:32 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Catalina]
4月 15, 2019 9:30:32 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet engine: [Apache Tomcat/9.0.17]
4月 15, 2019 9:30:32 下午 org.apache.catalina.startup.HostConfig deployDescriptor
信息: Deploying deployment descriptor [D:\workspace\eclipse-web\apache-tomcat-9.0.17\conf\Catalina\localhost\TocmatTest.xml]
4月 15, 2019 9:30:32 下午 org.apache.catalina.startup.HostConfig deployDescriptor
警告: The path attribute with value [/TocmatTest] in deployment descriptor [D:\workspace\eclipse-web\apache-tomcat-9.0.17\conf\Catalina\localhost\TocmatTest.xml] has been ignored
4月 15, 2019 9:30:32 下午 org.apache.catalina.startup.HostConfig deployDescriptor
警告: Deployment of deployment descriptor [D:\workspace\eclipse-web\apache-tomcat-9.0.17\conf\Catalina\localhost\TocmatTest.xml] with an external docBase means the directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\TocmatTest] in the appBase will be ignored
4月 15, 2019 9:30:33 下午 org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
警告: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [528] milliseconds.
4月 15, 2019 9:30:33 下午 org.apache.catalina.startup.HostConfig deployDescriptor
信息: Deployment of deployment descriptor [D:\workspace\eclipse-web\apache-tomcat-9.0.17\conf\Catalina\localhost\TocmatTest.xml] has finished in [1,258] ms
4月 15, 2019 9:30:33 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 應(yīng)用程序部署到目錄 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\docs]
4月 15, 2019 9:30:33 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\docs] has finished in [66] ms
4月 15, 2019 9:30:33 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 應(yīng)用程序部署到目錄 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\examples]
4月 15, 2019 9:30:34 下午 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextInitialized()
4月 15, 2019 9:30:34 下午 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextInitialized()
4月 15, 2019 9:30:34 下午 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: attributeAdded('StockTicker', 'async.Stockticker@437e951d')
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\examples] has finished in [660] ms
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 應(yīng)用程序部署到目錄 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\host-manager]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\host-manager] has finished in [59] ms
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 應(yīng)用程序部署到目錄 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\manager]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\manager] has finished in [104] ms
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 應(yīng)用程序部署到目錄 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\ROOT]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\ROOT] has finished in [57] ms
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 應(yīng)用程序部署到目錄 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\WebContent]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\WebContent] has finished in [58] ms
4月 15, 2019 9:30:34 下午 org.apache.coyote.AbstractProtocol start
信息: 開始協(xié)議處理句柄["http-nio-8080"]
4月 15, 2019 9:30:34 下午 org.apache.coyote.AbstractProtocol start
信息: 開始協(xié)議處理句柄["ajp-nio-8009"]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in [2,502] milliseconds
4月 15, 2019 9:49:16 下午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/TocmatTest] has started
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.catalina.loader.WebappClassLoaderBase (file:/D:/workspace/eclipse-web/apache-tomcat-9.0.17/lib/catalina.jar) to field java.io.ObjectStreamClass$Caches.localDescs
WARNING: Please consider reporting this to the maintainers of org.apache.catalina.loader.WebappClassLoaderBase
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
4月 15, 2019 9:49:17 下午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/TocmatTest] is completed
總結(jié)
以上是生活随笔為你收集整理的futurejava前台_web前端页面与后端Java的数据交互的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: echarts无数据时显示无数据_钣金无
- 下一篇: resultmap的写法_mybatis