pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaNative</groupId> <artifactId>JavaNative</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>JavaNative</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.glassfish.tyrus.bundles</groupId> <artifactId>tyrus-standalone-client</artifactId> <version>1.9</version> </dependency> </dependencies> </project>
websocket.client.SimpleClient
package websocket.client;
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
/**
* Created by Administrator on 2016/4/17.
*/
@ClientEndpoint
public class SimpleClient {
@OnOpen
public void onOpen(Session session) {
System.out.println("open ... ");
}
@OnMessage
public void onMessage(String message) {
System.out.println(message);
}
@OnError
public void onError(Throwable t) {
t.printStackTrace();
}
public static void main(String[] args)throws Exception{
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri ="ws://localhost:8077/web/SimpleWebSocket";
System.out.println("Connecting to 2"+ uri);
Session session = container.connectToServer(SimpleClient.class, URI.create(uri));
session.getBasicRemote().sendText("这是从java客户端发送的消息 。。。");
Thread.sleep(1000);
session.close();
}
}原文:http://antlove.blog.51cto.com/10057557/1764845