javawebsocket
A. java中怎麼使用websocket
伺服器端實現(Tomcat)
客戶端實現(Java-WebSocket)
客戶端實現(Javascript原生API)
B. 怎樣用java web和websocket實現網頁即時通訊
java 後台做 websocket 服務端。 頁面使用js的websocket客戶端 連接上 服務端 就能實時通信了。
C. java socket 怎麼給websocket發信息
1.InitServlet
該類主要是用來初始化構造將來存儲用戶身份信息的map倉庫,利用其初始化方法Init 初始化倉庫, 利用其靜態方法getSocketList 獲得對應的用戶身份信息。
webSocket ,我認為MessageInbound 用來識別登錄人的信息,用它來找到對應的人,推送消息。每次登錄都會產生一個MessageInbound。
這里的HashMap<String,MessageInbound> :string 存儲用戶session的登錄id,MessageInbound存儲 推送需要的身份信息。以上屬於個人口頭話理解。
packagesocket;
importjava.nio.CharBuffer;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjavax.servlet.ServletConfig;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importorg.apache.catalina.websocket.MessageInbound;
{
=-3163557381361759907L;
//privatestaticList<MessageInbound>socketList;
privatestaticHashMap<String,MessageInbound>socketList;
publicvoidinit(ServletConfigconfig)throwsServletException{
//InitServlet.socketList=newArrayList<MessageInbound>();
InitServlet.socketList=newHashMap<String,MessageInbound>();
super.init(config);
System.out.println("Serverstart============");
}
publicstaticHashMap<String,MessageInbound>getSocketList(){
returnInitServlet.socketList;
}
/*publicstaticList<MessageInbound>getSocketList(){
returnInitServlet.socketList;
}
*/}
2.MyWebSocketServlet
websocket用來建立連接的servlet,建立連接時,首先在session獲取該登錄人的userId,在調用MyMessageInbound構造函數傳入userId
packagesocket;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.nio.CharBuffer;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.catalina.websocket.StreamInbound;
importorg.apache.catalina.websocket.WebSocketServlet;
/**
*
*@ClassName:MyWebSocketServlet
*@Description:建立連接時創立
*@authormangues
*@date2015-7-19
*/
{
publicStringgetUser(HttpServletRequestrequest){
StringuserName=(String)request.getSession().getAttribute("user");
if(userName==null){
returnnull;
}
returnuserName;
//return(String)request.getAttribute("user");
}
@Override
(Stringarg0,
HttpServletRequestrequest){
System.out.println("##########");
returnnewMyMessageInbound(this.getUser(request));
}
}
3.onOpen方法調用InitServlet的map身份倉庫,
放入用戶userId 和 對應該登錄用戶的websocket身份信息MessageInbound (可以用userId來尋找到推送需要的 身份MessageInbound)
onTextMessage :用來獲取消息,並發送消息
packagesocket;
importjava.io.IOException;
importjava.nio.ByteBuffer;
importjava.nio.CharBuffer;
importjava.util.HashMap;
importorg.apache.catalina.websocket.MessageInbound;
importorg.apache.catalina.websocket.WsOutbound;
importutil.MessageUtil;
{
privateStringname;
publicMyMessageInbound(){
super();
}
publicMyMessageInbound(Stringname){
super();
this.name=name;
}
@Override
protectedvoidonBinaryMessage(ByteBufferarg0)throwsIOException{
//TODOAuto-generatedmethodstub
}
@Override
protectedvoidonTextMessage(CharBuffermsg)throwsIOException{
//用戶所發消息處理後的map
HashMap<String,String>messageMap=MessageUtil.getMessage(msg);//處理消息類
//上線用戶集合類map
HashMap<String,MessageInbound>userMsgMap=InitServlet.getSocketList();
StringfromName=messageMap.get("fromName");//消息來自人的userId
StringtoName=messageMap.get("toName");//消息發往人的userId
//獲取該用戶
MessageInboundmessageInbound=userMsgMap.get(toName);//在倉庫中取出發往人的MessageInboundif(messageInbound!=null){//如果發往人存在進行操作
WsOutboundoutbound=messageInbound.getWsOutbound();
Stringcontent=messageMap.get("content");//獲取消息內容
StringmsgContentString=fromName+""+content;//構造發送的消息
//發出去內容
CharBuffertoMsg=CharBuffer.wrap(msgContentString.toCharArray());
outbound.writeTextMessage(toMsg);//
outbound.flush();
}/*for(MessageInboundmessageInbound:InitServlet.getSocketList()){
CharBufferbuffer=CharBuffer.wrap(msg);
WsOutboundoutbound=messageInbound.getWsOutbound();
outbound.writeTextMessage(buffer);
outbound.flush();
}*/
}
@Override
protectedvoidonClose(intstatus){
InitServlet.getSocketList().remove(this);
super.onClose(status);
}
@Override
protectedvoidonOpen(WsOutboundoutbound){
super.onOpen(outbound);
//登錄的用戶注冊進去
if(name!=null){
InitServlet.getSocketList().put(name,this);
}
//InitServlet.getSocketList().add(this);
}
}
4.消息處理類,處理前端發來的消息
packageutil;
importjava.nio.CharBuffer;
importjava.util.HashMap;
/**
*
*@ClassName:MessageUtil
*@Description:消息處理類
*@authormangues
*@date2015-7-19
*/
publicclassMessageUtil{
publicstaticHashMap<String,String>getMessage(CharBuffermsg){
HashMap<String,String>map=newHashMap<String,String>();
StringmsgString=msg.toString();
Stringm[]=msgString.split(",");
map.put("fromName",m[0]);
map.put("toName",m[1]);
map.put("content",m[2]);
returnmap;
}
}
D. 如何使用 java websocketclient
client.htm
<!DOCTYPE html>
<html>
<body>
<h1>WebSocket</h1>
<script src="client.js"></script>
</body>
</html>
client.js
var ws = new WebSocket("ws://127.0.0.1:8080/");
ws.onopen = function() {
alert("Opened");
ws.send("I'm client");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
ws.onclose = function() {
alert("Closed");
};
ws.onerror = function(err) {
alert("Error: " + err);
};
服務端可以用各種語言去實現,Java可以用Jetty,C#可以用SuperSocket,這里我舉例用Node.js,創建server.js:
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({port: 8080});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
});
ws.send('something');
});
運行方式:
npm install ws
node server.js
E. java websocket 怎麼啟動service
java websocket 啟動service的方法:
/**
* 當連接建立成功的時候觸發
*
* @param session
*/
@Resource
private IPhoneService phoneService;
/* private IPhoneService phoneService;
public void setIPhoneService(IPhoneService phoneService){
this.phoneService=phoneService;
}*/
@OnOpen
public void onOpen(Session session) {
logger_.info("Web-socket session " + session.getId() + " connected.");
try {
for (Session sess : session.getOpenSessions()) {
sess.getBasicRemote().sendText("Session " + session.getId() + " 加入連接 ");
}
} catch (Exception e) {
}
}
/**
* 當接收到消息的時候觸發
*
* @param message
* @param session
*/
@SuppressWarnings("static-access")
@OnMessage
public void onMessage(String message, Session session) {
logger_.info("Received message: '" + message + "'. from session: "
+ session.getId() + ". Thread ID: "
+ Thread.currentThread().getId());
try {
// 延遲發送消息
Thread.currentThread().sleep(StaticValues.REFRESH_TIME);
// 向前台發送消息
for (Session sess : session.getOpenSessions()) {
if (session == null) {
return;
}
/* ApplicationContext ac = new ("spring/mvc.xml");//新加1
AutowireCapableBeanFactory factory = ac.getAutowireCapableBeanFactory();
EmbedDaoImpl bean = factory.createBean(EmbedDaoImpl.class);*/
System.out.println(phoneService);
sess.getBasicRemote().sendText(session.getId() + ": " + message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
F. java怎麼做websocket
我不知道你想用websocket實現什麼樣的功能,一般配合HTML5的話可以解決服務端和客戶端消息實時傳遞的問題,如消息推送(webQQ這種)。它的初始連接是http轉成websocket連接。
實現的話要做兩件事,一端是在伺服器實現service,這個有點像tcplistener一樣;
另一個是客戶端(瀏覽器)開發,可以用JS實現:
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript">
var host = '127.0.0.1';
var port = 8080;
var url = 'ws://'+host+':'+port+'/';
var w = new WebSocket(url); //構建於伺服器之間的連接通信
<!--var audioElement = document.createElement('audio'); -->
<!--audioElement.setAttribute('src', 'qqmsg.mp3');-->
w.onopen = function()//通過onopen事件句柄來監聽socket的打開事件
{
$('chat-box').innerHTML = '已連接到伺服器......<br/>';
}
w.onmessage = function(e)//用onmessage事件句柄接受伺服器傳過來的數據
{
var msg = e.data;
var chatBox = $('chat-box');
// audioElement.play();
chatBox.innerHTML = chatBox.innerHTML+msg+'<br/>';
}
function send()//使用send方法向伺服器發送數據
{
var talk = $('talk');
var nike = $('nike');
w.send('<strong style="color:red">'+nike.value+':</strong>'+talk.value);
}
function $(id)
{
return document.getElementById(id);
}
</script>
</head>
<body>
<div id="chat-box" style="border:1px solid #cccccc; width:400px; height:400px; overflow:scroll;"></div>
昵稱:
<input type="text" id="nike"/>
<br/>
內容:
<input type="text" id="talk"/>
<input type="button" id="send" onClick="send();" value="發送"/>
</body>
可參考IBM社區 http://www.ibm.com/developerworks/cn/web/1112_huangxa_websocket/
</html>
G. java socket怎麼與websocket對接
這個問題問的不是很專業!准確的說,應該是java如何開發一個websocket協議的服務端程序回與js前端對接!因答為java socket不是一種協議,他是tcp的實現,而websocket則是一種協議(類似與HTTP,但與其不完全相同).至於實現方式,在tomcat7中的自帶的javax打頭的jar包中,就有對於websocket的支持,如果你創建了一個web項目,並且引用了tomcat7的server runtime,那麼你可以直接對一個編寫好的類進行改造成一個websocket的服務端!
比如:
@ServerEndpoint("/wsdemo")//此處指定訪問地址,記得埠為tomcat配置的埠,即ws://localhost:8080/projectName/wsdemo
publicclassWsDemo{
@OnMessage//直接加註釋即可//其他的OnError等類似的
publicvoidOnMessage(xxxEventevent){//單詞忘了....
event.getBaseRemote().sendText("");//向客戶端發送信息
}
}