栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java服务器JavaScript客户端WebSocket

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java服务器JavaScript客户端WebSocket

首先,您的两个代码看起来与Java和Javascript完全相同。两者都可以按照他们设计的目的工作,但是事实是您正在尝试将WebSocket客户端连接到套接字服务器。

据我所知,关于这个答案,他们是两回事。

我从来没有尝试过你的方式。这就是说,如果我有一个使用套接字的网络应用程序,那么它将是纯客户端/服务器套接字;如果它是一个Web应用程序,那么我将在两侧都使用WebSocket。

到目前为止,一切都很好..

我正在使用Java的WebSocket,这是我已经用您的客户端代码测试过的示例实现,并且可以在客户端和服务器端使用。

import org.java_websocket.WebSocket;import org.java_websocket.handshake.ClientHandshake;import org.java_websocket.server.WebSocketServer;import java.net.InetSocketAddress;import java.util.HashSet;import java.util.Set;public class WebsocketServer extends WebSocketServer {    private static int TCP_PORT = 4444;    private Set<WebSocket> conns;    public WebsocketServer() {        super(new InetSocketAddress(TCP_PORT));        conns = new HashSet<>();    }    @Override    public void onOpen(WebSocket conn, ClientHandshake handshake) {        conns.add(conn);        System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());    }    @Override    public void onClose(WebSocket conn, int pre, String reason, boolean remote) {        conns.remove(conn);        System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());    }    @Override    public void onMessage(WebSocket conn, String message) {        System.out.println("Message from client: " + message);        for (WebSocket sock : conns) { sock.send(message);        }    }    @Override    public void onError(WebSocket conn, Exception ex) {        //ex.printStackTrace();        if (conn != null) { conns.remove(conn); // do some thing if required        }        System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());    }}

在您的主要方法上:

new WebsocketServer().start();

您可能需要操纵您的代码以使其适合此实现,但这应该是工作的一部分。

这是2个测试的测试输出:

New connection from 127.0.0.1Message from client: PingClosed connection to 127.0.0.1New connection from 127.0.0.1Message from client: Ping

这是WebSocket maven配置,否则手动下载JAR文件并导入到您的IDE /开发环境中:

<!-- https://mvnrepository.com/artifact/org.java-websocket/Java-WebSocket --><dependency>    <groupId>org.java-websocket</groupId>    <artifactId>Java-WebSocket</artifactId>    <version>1.3.0</version></dependency>

链接到WebSocket。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/609955.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号