WebSocket
2016-06-05 16:49
501 查看
服务器代码:
1、首先建立web服务器
2、导入包(地址:<a href="http://download.csdn.net/detail/qq_19984993/9541820">jar包地址</a>)
2、创建类
注意:@ServerEndpoint(value = "/websocket/chat")用于表示URL的访问地址
@ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {
private static final Logger log = Logger.getLogger(ChatAnnotation.class.getName());
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<ChatAnnotation> connections =
new CopyOnWriteArraySet<ChatAnnotation>();
private final String nickname;
private Session session;
public ChatAnnotation() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
@OnOpen
public void start(Session session) {
this.session = session;
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
connections.add(this);
}
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
}
@OnMessage
public void incoming(String message) {
// Never trust the client
String filteredMessage = String.format("%s: %s",
nickname, message.toString());
broadcast(filteredMessage);
}
@OnError
public void onError(Throwable t) throws Throwable {
log.info("Chat Error: " + t.toString());
}
private static void broadcast(String msg) {
for (ChatAnnotation client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
log.info("Chat Error: Failed to send message to client"+e.getMessage());
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
String message = String.format("* %s %s",
client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}
访问地址为:ws://localhost:8080/myWebSocket/websocket/chat
java客户端
java客户端使用的是java_websocket框架需要导入java_websocket.jar包(<a href="http://download.csdn.net/detail/qq_19984993/9541826">jar包地址</a>)
创建类:
public class MyClient extends WebSocketClient{
public MyClient(URI serverUri, Draft draft) {
super(serverUri, draft);
// TODO Auto-generated constructor stub
}
@Override
public void onMessage( String message ) {
// send("hello");
System.out.println("reciver"+message);
}
@Override
public void onError( Exception ex ) {
ex.printStackTrace();
}
@Override
public void onOpen( ServerHandshake handshake ) {
System.out.println("open");
}
@Override
public void onClose( int code, String reason, boolean remote ) {
send("I will go");
}
测试:
String uri = "ws://localhost:8080/myWebSocket/websocket/chat";
MyClient client = new MyClient(URI.create(uri),new Draft_17());
try {
ok = client.connectBlocking();
client.close();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
1、首先建立web服务器
2、导入包(地址:<a href="http://download.csdn.net/detail/qq_19984993/9541820">jar包地址</a>)
2、创建类
注意:@ServerEndpoint(value = "/websocket/chat")用于表示URL的访问地址
@ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {
private static final Logger log = Logger.getLogger(ChatAnnotation.class.getName());
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<ChatAnnotation> connections =
new CopyOnWriteArraySet<ChatAnnotation>();
private final String nickname;
private Session session;
public ChatAnnotation() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
@OnOpen
public void start(Session session) {
this.session = session;
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
connections.add(this);
}
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
}
@OnMessage
public void incoming(String message) {
// Never trust the client
String filteredMessage = String.format("%s: %s",
nickname, message.toString());
broadcast(filteredMessage);
}
@OnError
public void onError(Throwable t) throws Throwable {
log.info("Chat Error: " + t.toString());
}
private static void broadcast(String msg) {
for (ChatAnnotation client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
log.info("Chat Error: Failed to send message to client"+e.getMessage());
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
String message = String.format("* %s %s",
client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}
访问地址为:ws://localhost:8080/myWebSocket/websocket/chat
java客户端
java客户端使用的是java_websocket框架需要导入java_websocket.jar包(<a href="http://download.csdn.net/detail/qq_19984993/9541826">jar包地址</a>)
创建类:
public class MyClient extends WebSocketClient{
public MyClient(URI serverUri, Draft draft) {
super(serverUri, draft);
// TODO Auto-generated constructor stub
}
@Override
public void onMessage( String message ) {
// send("hello");
System.out.println("reciver"+message);
}
@Override
public void onError( Exception ex ) {
ex.printStackTrace();
}
@Override
public void onOpen( ServerHandshake handshake ) {
System.out.println("open");
}
@Override
public void onClose( int code, String reason, boolean remote ) {
send("I will go");
}
测试:
String uri = "ws://localhost:8080/myWebSocket/websocket/chat";
MyClient client = new MyClient(URI.create(uri),new Draft_17());
try {
ok = client.connectBlocking();
client.close();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
相关文章推荐
- 2015-2016网页设计趋势分析 Web Design of Trends
- Apache Isis 1.4.0 发布,领域驱动开发框架
- RH436 Day3 课后总结
- Linux快速构建apache web服务器
- Awstats处理多apache日志
- 安装perl模块小窍门
- Apache静态编译与动态编译的区别
- PHP+Apache在Windows 9x下的安装和配置
- Apache服务器配置全攻略
- Apache Web让JSP“动”起来
- Linux Apache+MySQL+PHP
- 建立Apache+PHP+MySQL数据库驱动的动态网站
- apache 环境下 php 的配置注意事项
- 在RedHat下安装apache jserv 1.1.2方法
- windows8.1下Apache+Php+MySQL配置步骤
- windows中PHP5.2.14以及apache2.2.16安装配置方法第1/2页
- 在Windows XP下安装Apache+MySQL+PHP环境
- 解析阿里云ubuntu12.04环境下配置Apache+PHP+PHPmyadmin+MYsql
- apache rewrite防盗链三例
- Apache 配置详解(最好的APACHE配置教程)