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("");//向客户端发送信息
}
}