java怎么关闭socket_用Java关闭websocket连接

本文介绍如何在Java WebSocket API中关闭WebSocket连接。通过在ClientEndpoint类中使用Session对象的close方法,可以在主线程结束前正确关闭WebSocket连接。示例代码展示了启动和关闭WebSocket连接的详细步骤。
摘要由CSDN通过智能技术生成

如何使用

Java WebSocket API关闭websocket连接?我已经将Java websocket API用于服务器端点和客户端端点.该应用程序运行正常.但是在主线程结束之前我不知道如何关闭websocket.

这是我的ClientEndpoint

package websocket.client;

import java.io.IOException;

import javax.websocket.MessageHandler;

import javax.websocket.OnError;

import javax.websocket.OnMessage;

import javax.websocket.OnOpen;

import javax.websocket.Session;

@ClientEndpoint

public class EchoClient {

Session session;

//request

@OnOpen

public void onOpen(Session session, EndpointConfig config) {

System.out.println("Connected to endpoint: " + session.getBasicRemote());

this.session = session;

sendMessage("Welcome to WebSocket");

}

//response

@OnMessage

public void onMessage(String text) {

System.out.println("Received response in client from server: " + text);

}

@OnError

public void onError(Session session, Throwable t) {

t.printStackTrace();

}

private void sendMessage(String message) {

System.out.println("Sending message from client to server: " + message);

System.out.println(session);

try {

session.getBasicRemote().sendText(message);

} catch (IOException e) {

e.printStackTrace();

}

}

}

我使用以下代码启动ClientEndPoint

import java.io.IOException;

import java.net.URI;

import javax.websocket.ContainerProvider;

import javax.websocket.DeploymentException;

import javax.websocket.WebSocketContainer;

import websocket.client.EchoClient;

public class WebSocketDemo {

public static void main(String[] args) {

String uri = "ws://localhost:8080/websocket";

System.out.println("Connecting to " + uri);

WebSocketContainer container = ContainerProvider.getWebSocketContainer();

try {

container.connectToServer(EchoClient.class, URI.create(uri));

} catch (DeploymentException | IOException e) {

e.printStackTrace();

}

try {

Thread.sleep(5000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

PS:我没有使用过JavaScript.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值