写在前面
新公司用到了websocket技术,所以这里学习下。
1:Java原生
1.1:maven
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.3</version>
</dependency>
1.2:server
public class SocketServer extends WebSocketServer {
public SocketServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
}
public SocketServer(InetSocketAddress address) {
super(address);
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
conn.send("Welcome to the server!"); // This method sends a message to the new client
broadcast("new connection: " + handshake
.getResourceDescriptor()); // This method sends a message to all clients connected
System.out.println(
conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
broadcast(conn + " has left the room!");
System.out.println(conn + " has left the room!");
}
@Override
public void onMessage(WebSocket conn, String message) {
broadcast(message + "by server");
System.out.println(conn + ": " + message);
}
@Override
public void onError(WebSocket conn, Exception ex) {
ex.printStackTrace();
if (conn != null) {
// some errors like port binding failed may not be assignable to a specific
// websocket
}
}
@Override
public void onStart() {
System.out.println("Server started!");
setConnectionLostTimeout(0);
setConnectionLostTimeout(100);
}
}
1.3:main
public class MyMain {
public static void main(String[] args) throws InterruptedException, IOException {
int port = 8887; // 843 flash policy port
SocketServer s = new SocketServer(port);
s.start();
System.out.println("ChatServer started on port: " + s.getPort());
BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String in = sysin.readLine();
s.broadcast(in);
if (in.equals("exit")) {
s.stop(1000);
break;
}
}
}
}
启动:
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
ChatServer started on port: 8887
Server started!
1.4:测试
我们使用如下的工具 来测试:
在地址框录入地址ws://localhost:8887
,测试如下:
可以再调试工具查看交互的过程:
2:java原生+springboot
2.1:pom
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.7.7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
2.2:程序
- 定义连接端点endpoint
@ServerEndpoint("/myWs")
@Component
public class WsServerEndpoint {
/**
* 连接成功
*
* @param session
*/
@OnOpen
public void onOpen(Session session) {
System.out.println("连接成功");
}
/**
* 连接关闭
*
* @param session
*/
@OnClose
public void onClose(Session session) {
System.out.println("连接关闭");
}
/**
* 接收到消息
*
* @param text
*/
@OnMessage
public String onMsg(String text) throws IOException {
return "servet 发送:" + text;
}
}
- 暴漏服务
@Configuration
@EnableWebSocket
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpoint() {
return new ServerEndpointExporter();
}
}
- main
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
启动:
...
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.7)
2023-11-17 11:26:14.827 INFO 24100 --- [ main] a.b.App : Starting App using Java 1.8.0_202 on DESKTOP-C3DTETT with PID 24100 (E:\workspace-idea\dongshidaddy-labs-new\javabase\websocket\java_origin_and_boot\target\classes started by dell9020 in E:\workspace-idea\dongshidaddy-labs-new)
2023-11-17 11:26:14.891 INFO 24100 --- [ main] a.b.App : No active profile set, falling back to 1 default profile: "default"
...
2023-11-17 11:26:50.299 INFO 24100 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
- 测试
写在后面
参考文章列表
java实现websocket的五种方式 。