服务器代码:
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();
}