Python客户端未从Spring WebSocket服务器接收消息 [英] Python client doesn't receive messages from Spring websocket server

查看:83
本文介绍了Python客户端未从Spring WebSocket服务器接收消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该项目的目标是使JVM(Kotlin)服务器和Python客户端通过WebSocket相互通信.服务器必须将更新发送给客户端,客户端将处理这些更新.

该服务器是运行Spring Boot Websocket服务器的Spring Boot应用程序.客户端现在只是一个Python脚本,运行websocket-client连接到服务器.

工作原理:

  • 列表项
  • 客户端可以连接到服务器
  • 客户端可以连接到服务器上的主题(使用STOMP)
  • 客户端可以向服务器发送消息,并且服务器接收并处理该消息
  • 服务器可以在网络套接字上发送消息

什么不起作用:

  • 客户端未收到来自服务器的消息

我通过连接到websocket.org的回显服务器(ws://echo.websocket.org)尝试了客户端的接收部分,客户端从服务器接收了回显的消息.因此在我看来,问题不在客户端.


代码时间.

Kotlin服务器:用于创建websocket服务器的代码:

 程序包nl.sajansen.screenchangenotifierserver导入org.springframework.beans.factory.annotation.Autowired导入org.springframework.context.annotation.Configuration导入org.springframework.messaging.handler.annotation.MessageMapping导入org.springframework.messaging.simp.SimpMessagingTemplate导入org.springframework.messaging.simp.config.MessageBrokerRegistry导入org.springframework.scheduling.annotation.Scheduled导入org.springframework.stereotype.Controller导入org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker导入org.springframework.web.socket.config.annotation.StompEndpointRegistry导入org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer导入java.time.Instant导入java.time.format.DateTimeFormatter@配置@EnableWebSocketMessageBrokerWebSocketConfig类:WebSocketMessageBrokerConfigurer {覆盖有趣的registerStompEndpoints(registry:StompEndpointRegistry){Registry.addEndpoint("/ws").setAllowedOrigins("*")}覆盖有趣的configureMessageBroker(config:MessageBrokerRegistry){config.enableSimpleBroker("/topic","/queue")config.setApplicationDestinationPrefixes("/app")}}@控制器类WebsocketController @Autowired构造函数(val模板:SimpMessagingTemplate){@Scheduled(fixedDelayString ="1000")有趣的blastToClientsHostReport(){println(在网络套接字上发送内容")template.convertAndSend("/topic/greeting","Hello World");}@MessageMapping("/greeting")有趣的句柄(消息:字符串):字符串{println(收到的消息:$ message")template.convertAndSend("/topic/greeting",消息)返回"["+ getTimestamp()+":"+讯息}}有趣的getTimestamp():字符串= DateTimeFormatter.ISO_INSTANT.format(Instant.now()) 

Gradle依存关系等:

  import org.jetbrains.kotlin.gradle.tasks.KotlinCompile插件{id("org.springframework.boot")版本"2.1.9.RELEASE".id("io.spring.dependency-management")版本"1.0.8.RELEASE"kotlin("jvm")版本"1.2.71"kotlin("plugin.spring")版本"1.2.71"kotlin("plugin.jpa")版本"1.2.71"kotlin("plugin.allopen")版本"1.2.71"//对于JPA延迟获取}allOpen {注释("javax.persistence.Entity")注释("javax.persistence.Embeddable")注释("javax.persistence.MappedSuperclass")}储存库{mavenCentral()}依赖项{实现("org.springframework.boot:spring-boot-starter-data-jpa")runtimeOnly("com.h2database:h2:1.4.197")//固定版本作为https://github.com/h2database/h2database/issues/1841的解决方法实现("org.springframework.boot:spring-boot-starter-web")实现("com.fasterxml.jackson.module:jackson-module-kotlin")实施("org.jetbrains.kotlin:kotlin-reflect")实施("org.jetbrains.kotlin:kotlin-stdlib-jdk8")testImplementation("org.springframework.boot:spring-boot-starter-test"){排除(模块="junit")exclude(模块="mockito-core")}testImplementation("org.junit.jupiter:junit-jupiter-api")testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")testImplementation("com.ninja-squad:springmockk:1.1.2")编译("org.springframework.boot:spring-boot-starter-websocket")}task.withType< KotlinCompile>{kotlinOptions {freeCompilerArgs = listOf(-Xjsr305 = strict")jvmTarget ="1.8"}}task.withType< Test>{useJUnitPlatform()} 

Python客户端:

 随机导入将踩脚导入为踩脚导入websocketdef main():websocket.enableTrace(真)#连接到websocketws = websocket.create_connection("ws://localhost:8080/ws")#订阅主题client_id = str(random.randint(0,1000))sub = stomper.subscribe("/topic/greeting",client_id,ack ='auto')ws.send(sub)#发送一些消息ws.send(stomper.send("/app/greeting","Hello there")))而True:打印(接收数据:")d = ws.recv()打印(d)如果__name__ =='__main__':主要的() 

Pip依赖项:

  opencv-python == 4.1.1.26websocket-client == 0.56.0踩踏== 0.4.3 


控制台输出

现在,服务器的控制台输出是这个.可以看到,当客户端未连接时,没有订阅者发送已调度的消息.比客户端成功连接,计划的消息广播到1个订阅者.

 在网络套接字上发送某些内容2019-10-17 12:45:09.425调试32285-[MessageBroker-3] org.springframework.web.SimpLogging:处理MESSAGE目的地=/主题/问候会话=空有效负载= Hello World在网络套接字上发送一些东西2019-10-17 12:45:10.426调试32285-[MessageBroker-3] org.springframework.web.SimpLogging:处理MESSAGE目的地=/主题/问候会话=空有效负载= Hello World2019-10-17 12:45:10.849信息32285-[nio-8080-exec-1] o.a.c.c.C. [Tomcat].[localhost].[/]:初始化Spring DispatcherServlet'dispatcherServlet'2019-10-17 12:45:10.850 INFO 32285-[nio-8080-exec-1] o.s.web.servlet.DispatcherServlet:初始化Servlet'dispatcherServlet'2019-10-17 12:45:10.850调试32285-[nio-8080-exec-1] o.s.web.servlet.DispatcherServlet:检测到StandardServletMultipartResolver2019-10-17 12:45:10.855调试32285-[nio-8080-exec-1] osweb.servlet.DispatcherServlet:enableLoggingRequestDetails ='true':将显示请求参数和标头,这可能会导致不安全的日志记录潜在敏感数据2019-10-17 12:45:10.855信息32285-[nio-8080-exec-1] o.s.web.servlet.DispatcherServlet:在5毫秒内完成初始化2019-10-17 12:45:10.861调试32285-[nio-8080-exec-1] o.s.web.servlet.DispatcherServlet:GET"/ws",parameters = {}2019-10-17 12:45:10.865调试32285-[nio-8080-exec-1] o.s.w.s.s.s.WebSocketHandlerMapping:映射到org.springframework.web.socket.server.support.WebSocketHttpRequestHandler@27a9f0252019-10-17 12:45:10.872调试32285-[nio-8080-exec-1] o.s.w.s.s.s.WebSocketHttpRequestHandler:GET/ws2019-10-17 12:45:10.885调试32285-[nio-8080-exec-1] o.s.web.servlet.DispatcherServlet:已完成101 SWITCHING_PROTOCOLS2019-10-17 12:45:10.901调试32285-[nio-8080-exec-1] swshLoggingWebSocketHandlerDecorator:New StandardWebSocketSession [id = 393fc3cd-9ca3-1749-1ea8-541def6592e0,uri = ws://localhost:8080/ws]2019-10-17 12:45:10.912调试32285 --- [nboundChannel-2] org.springframework.web.SimpLogging:处理SUBSCRIBE/topic/greeting id = 216 session = 393fc3cd-9ca3-1749-1ea8-541def6592e02019-10-17 12:45:10.914调试32285-[nboundChannel-7] .WebSocketAnnotationMethodMessageHandler:搜索处理SEND的方法/app/greeting session = 393fc3cd-9ca3-1749-1ea8-541def6592e0 text/plain payload = Hello,lookupDestination ='/greeting'2019-10-17 12:45:10.915调试32285-[nboundChannel-7] .WebSocketAnnotationMethodMessageHandler:调用nl.sajansen.screenchangenotifierserver.WebsocketController#handle [1 args]收到消息:您好2019-10-17 12:45:10.916调试32285-[nboundChannel-7] org.springframework.web.SimpLogging:处理MESSAGE目的地=/主题/问候会话=空有效载荷=你好2019-10-17 12:45:10.916调试32285-[nboundChannel-7] org.springframework.web.SimpLogging:广播到1个会话.2019-10-17 12:45:10.919调试32285 --- [nboundChannel-7] org.springframework.web.SimpLogging:处理MESSAGE目的地=/topic/问候会话= 393fc3cd-9ca3-1749-1ea8-541def6592e0有效载荷= [2019-10-17T10:45:10.917Z:你好2019-10-17 12:45:10.919调试32285-[nboundChannel-7] org.springframework.web.SimpLogging:广播到1个会话.在网络套接字上发送一些东西2019-10-17 12:45:11.427调试32285-[MessageBroker-3] org.springframework.web.SimpLogging:处理MESSAGE目的地=/主题/问候会话=空有效负载= Hello World 

客户端的输出是这样,但是只是等到世界末日才能收到消息:

  ---请求标头---GET/ws HTTP/1.1升级:websocket连接方式:升级主机:localhost:8080来源:http://localhost:8080Sec-WebSocket-密钥:8ihHk0C5C0nji4s7u4atZQ ==安全WebSocket版本:13--------------------------响应头---HTTP/1.1 101升级:websocket连接方式:升级Sec-WebSocket-接受:Drq8 +/vJkXkvToB3/AuCGMdYwuo =日期:2019年10月17日,星期四10:45:10 GMT-----------------------发送:b'\ x81 \ xb9 \ x88k \ xa6j \ xdb> \ xe49 \ xcb9 \ xef(\ xcda \ xcf \ x0e \ xb2Y \ x97 \\\ x82 \ x0f \ xc3 \ x19 \ x19 \ xfc \ x02 \ xc8 \ x0b\ xfc \ x02 \ xc9 \ x04 \ xb2D \ xd2 \ x05 \ xf8 \ x02 \ xc5E \ xef \ x19 \ xc3 \ x0f \ xfc \ x02 \ xc8 \ r \ x82 \ n \ xc5 \ x01 \ xb2 \ n \ xd3\ x1e \ xe7a \ xacj \ x82'发送:b'\ x81 \ xc5 \ xd0 \ x8dE6 \ x83 \ xc8 \ x0br \ xda \ xe9 E \ xa4 \ xe4 + W \ xa4 \ xe4 * X \ xea \ xa2 $ F \ xa0 \ xa2'D \ xb5 \xe81_ \ xbe \ xeaOU \ xbf \ xe31S \ xbe \ xf9hB \ xa9 \ xfd \ x0c \ xa4 \ xe8 = B \ xff \ xfd)W \ xb9 \ xe3O <\ x98 \ xe8)Z \ xbf \ xad1 ^ \ xb5 \xff 6 \ xda'接收数据: 


更多背景信息,以备您有更好的主意:更新将包含一个图像文件(可能编码为base64).更新必须实时发送(允许延迟不超过1秒).这些更新的间隔时间可能从几分钟到半秒不等.客户端和服务器是位于同一网络中的两台不同的计算机,但是该网络的吞吐量受到限制.


那么,谁能找出问题所在?

我已经阅读了本文档中有关Websocket的大部分内容,但看不到出了什么问题:这个答案也使我感触颇深,但是示例本身并未开始工作(纠正了 while not True 改为 while True ).

更新2019年10月18日:我正在寻找Python SocketJS客户端,因为我将Kotlin服务器部分与SocketJS和JavaScript客户端一起使用.但是我找不到任何Python SocketJS客户端实现..我想知道是否剩下的唯一解决方案是在Python应用程序(客户端)中启动websocket服务器,然后让客户端将其websocket服务器详细信息发送到Kotlin服务器,然后将连接到客户端的websocket服务器.这不是一个很好的解决方案,但我想知道它是否有效.我会及时通知您.

更新2021年2月1日:我没有花更多时间解决这个问题.但是,如果有人能解决这个问题,并且可以帮助其他人解决问题,我将保留此职位.

解决方案

上个月我也遇到了同样的问题.我假设您正在针对Python使用基于Web套接字的Stomp.提到 Websocket客户端未收到任何消息,我想你忘记启动连接.

因此,您应该从此更改python-client代码

  ...#连接到websocketws = websocket.create_connection("ws://localhost:8080/ws")#订阅主题client_id = str(random.randint(0,1000))sub = stomper.subscribe("/topic/greeting",client_id,ack ='auto')ws.send(sub)... 

进入此

 #连接到websocketws = websocket.create_connection("ws://localhost:8080/ws")#启动Stomp连接!ws.send("CONNECT \ naccept-version:1.0,1.1,2.0 \ n \ n \ x00 \ n")#订阅主题client_id = str(random.randint(0,1000))sub = stomper.subscribe("/topic/greeting",client_id,ack ='auto')ws.send(sub) 

我希望它能奏效.

尽管如此,我通过从 import websocket 库中实现 WebSocketApp 类来解决此问题,而不是执行诸如代码之类的程序性步骤.

Goal of the project is, is to have a JVM (Kotlin) server and a Python client communicating with each other by a websocket. The server must send updates to the client and the client will process these updates.

The server is a Spring Boot application, running the Spring Boot websocket server. The client is for now just a Python script, running websocket-client to connect to the server.

What is working:

  • List item
  • the client can connect to the server
  • the client can connect to a topic on the server (using STOMP)
  • the client can send a message to the server and the server receives and processes this message
  • the server can send a message on the websocket

What is not working:

  • the message from the server isn't received by the client

I've tried the receiving part of the client by connecting to the echo server of websocket.org (ws://echo.websocket.org) and the client receives the echoed messages from the server. So it seems to me that the problem isn't at the client side.


Code time.

Kotlin server: Code for creating the websocket server:

package nl.sajansen.screenchangenotifierserver

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.simp.SimpMessagingTemplate
import org.springframework.messaging.simp.config.MessageBrokerRegistry
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Controller
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker
import org.springframework.web.socket.config.annotation.StompEndpointRegistry
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer
import java.time.Instant
import java.time.format.DateTimeFormatter


@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig : WebSocketMessageBrokerConfigurer {
    override fun registerStompEndpoints(registry: StompEndpointRegistry) {
        registry.addEndpoint("/ws").setAllowedOrigins("*")
    }

    override fun configureMessageBroker(config: MessageBrokerRegistry) {
        config.enableSimpleBroker("/topic", "/queue")
        config.setApplicationDestinationPrefixes("/app")
    }
}

@Controller
class WebsocketController @Autowired constructor(val template: SimpMessagingTemplate) {
    @Scheduled(fixedDelayString = "1000")
    fun blastToClientsHostReport() {
        println("Sending something on the websocket")
        template.convertAndSend("/topic/greeting", "Hello World");
    }

    @MessageMapping("/greeting")
    fun handle(message: String): String {
        println("Received message: $message")
        template.convertAndSend("/topic/greeting", message)
        return "[" + getTimestamp() + ": " + message
    }
}

fun getTimestamp(): String = DateTimeFormatter.ISO_INSTANT.format(Instant.now())

Gradle dependencies etc.:

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "2.1.9.RELEASE"
    id("io.spring.dependency-management") version "1.0.8.RELEASE"
    kotlin("jvm") version "1.2.71"
    kotlin("plugin.spring") version "1.2.71"
    kotlin("plugin.jpa") version "1.2.71"
    kotlin("plugin.allopen") version "1.2.71"       // For JPA lazy fetching
}

allOpen {
    annotation("javax.persistence.Entity")
    annotation("javax.persistence.Embeddable")
    annotation("javax.persistence.MappedSuperclass")
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    runtimeOnly("com.h2database:h2:1.4.197") // Fixed version as a workaround for https://github.com/h2database/h2database/issues/1841
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    testImplementation("org.springframework.boot:spring-boot-starter-test") {
        exclude(module = "junit")
        exclude(module = "mockito-core")
    }
    testImplementation("org.junit.jupiter:junit-jupiter-api")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
    testImplementation("com.ninja-squad:springmockk:1.1.2")
    compile("org.springframework.boot:spring-boot-starter-websocket")
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "1.8"
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

Python client:

import random

import stomper as stomper
import websocket


def main():
  websocket.enableTrace(True)

  # Connecting to websocket
  ws = websocket.create_connection("ws://localhost:8080/ws")

  # Subscribing to topic
  client_id = str(random.randint(0, 1000))
  sub = stomper.subscribe("/topic/greeting", client_id, ack='auto')
  ws.send(sub)

  # Sending some message
  ws.send(stomper.send("/app/greeting", "Hello there"))

  while True:
    print("Receiving data: ")
    d = ws.recv()
    print(d)


if __name__ == '__main__':
  main()

Pip dependencies:

opencv-python==4.1.1.26
websocket-client==0.56.0
stomper==0.4.3


Console output

Now, the console output of the server is this. One can see that when the client isn't connected, there are no subscribers to send the scheduled message. Than the client connects successfully and the scheduled message is broadcasted to 1 subscriber.

Sending something on the websocket
2019-10-17 12:45:09.425 DEBUG 32285 --- [MessageBroker-3] org.springframework.web.SimpLogging      : Processing MESSAGE destination=/topic/greeting session=null payload=Hello World
Sending something on the websocket
2019-10-17 12:45:10.426 DEBUG 32285 --- [MessageBroker-3] org.springframework.web.SimpLogging      : Processing MESSAGE destination=/topic/greeting session=null payload=Hello World
2019-10-17 12:45:10.849  INFO 32285 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-10-17 12:45:10.850  INFO 32285 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-10-17 12:45:10.850 DEBUG 32285 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Detected StandardServletMultipartResolver
2019-10-17 12:45:10.855 DEBUG 32285 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : enableLoggingRequestDetails='true': request parameters and headers will be shown which may lead to unsafe logging of potentially sensitive data
2019-10-17 12:45:10.855  INFO 32285 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
2019-10-17 12:45:10.861 DEBUG 32285 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : GET "/ws", parameters={}
2019-10-17 12:45:10.865 DEBUG 32285 --- [nio-8080-exec-1] o.s.w.s.s.s.WebSocketHandlerMapping      : Mapped to org.springframework.web.socket.server.support.WebSocketHttpRequestHandler@27a9f025
2019-10-17 12:45:10.872 DEBUG 32285 --- [nio-8080-exec-1] o.s.w.s.s.s.WebSocketHttpRequestHandler  : GET /ws
2019-10-17 12:45:10.885 DEBUG 32285 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed 101 SWITCHING_PROTOCOLS
2019-10-17 12:45:10.901 DEBUG 32285 --- [nio-8080-exec-1] s.w.s.h.LoggingWebSocketHandlerDecorator : New StandardWebSocketSession[id=393fc3cd-9ca3-1749-1ea8-541def6592e0, uri=ws://localhost:8080/ws]
2019-10-17 12:45:10.912 DEBUG 32285 --- [nboundChannel-2] org.springframework.web.SimpLogging      : Processing SUBSCRIBE /topic/greeting id=216 session=393fc3cd-9ca3-1749-1ea8-541def6592e0
2019-10-17 12:45:10.914 DEBUG 32285 --- [nboundChannel-7] .WebSocketAnnotationMethodMessageHandler : Searching methods to handle SEND /app/greeting session=393fc3cd-9ca3-1749-1ea8-541def6592e0 text/plain payload=Hello there, lookupDestination='/greeting'
2019-10-17 12:45:10.915 DEBUG 32285 --- [nboundChannel-7] .WebSocketAnnotationMethodMessageHandler : Invoking nl.sajansen.screenchangenotifierserver.WebsocketController#handle[1 args]
Received message: Hello there
2019-10-17 12:45:10.916 DEBUG 32285 --- [nboundChannel-7] org.springframework.web.SimpLogging      : Processing MESSAGE destination=/topic/greeting session=null payload=Hello there
2019-10-17 12:45:10.916 DEBUG 32285 --- [nboundChannel-7] org.springframework.web.SimpLogging      : Broadcasting to 1 sessions.
2019-10-17 12:45:10.919 DEBUG 32285 --- [nboundChannel-7] org.springframework.web.SimpLogging      : Processing MESSAGE destination=/topic/greeting session=393fc3cd-9ca3-1749-1ea8-541def6592e0 payload=[2019-10-17T10:45:10.917Z: Hello there
2019-10-17 12:45:10.919 DEBUG 32285 --- [nboundChannel-7] org.springframework.web.SimpLogging      : Broadcasting to 1 sessions.
Sending something on the websocket
2019-10-17 12:45:11.427 DEBUG 32285 --- [MessageBroker-3] org.springframework.web.SimpLogging      : Processing MESSAGE destination=/topic/greeting session=null payload=Hello World

The output of the client is this, but just waits until the end of the world for a message to receive:

--- request header ---
GET /ws HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:8080
Origin: http://localhost:8080
Sec-WebSocket-Key: 8ihHk0C5C0nji4s7u4atZQ==
Sec-WebSocket-Version: 13


-----------------------
--- response header ---
HTTP/1.1 101
Upgrade: websocket
Connection: upgrade
Sec-WebSocket-Accept: Drq8+/vJkXkvToB3/AuCGMdYwuo=
Date: Thu, 17 Oct 2019 10:45:10 GMT
-----------------------
send: b'\x81\xb9\x88k\xa6j\xdb>\xe49\xcb9\xef(\xcda\xcf\x0e\xb2Y\x97\\\x82\x0f\xc3\x19\xfc\x02\xc8\x0b\xfc\x02\xc9\x04\xb2D\xd2\x05\xf8\x02\xc5E\xef\x19\xc3\x0f\xfc\x02\xc8\r\x82\n\xc5\x01\xb2\n\xd3\x1e\xe7a\xacj\x82'
send: b'\x81\xc5\xd0\x8dE6\x83\xc8\x0br\xda\xe9 E\xa4\xe4+W\xa4\xe4*X\xea\xa2$F\xa0\xa2"D\xb5\xe81_\xbe\xeaOU\xbf\xe31S\xbe\xf9hB\xa9\xfd \x0c\xa4\xe8=B\xff\xfd)W\xb9\xe3O<\x98\xe8)Z\xbf\xad1^\xb5\xff 6\xda'
Receiving data:


Some more background information in case you've better ideas: The updates will contain a image file (probably encoded to base64). The updates must be send close to realtime (allowed lag not more than 1 second). Interval of these updates can range from a couple of minutes to half a second. Client and server are two different machines, in the same network, but that network is limited on throughput.


So, who can spot what is going wrong?

I've read a good part of this document about websockets, but I can't see what is going wrong: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#websocket

This answer also got me far, but the example itself isn't working to begin with (after correcting the while not True to while True).

Update 18 Oct 2019: I looked for a Python SocketJS client, because I got the Kotlin server part working with SocketJS and a JavaScript client. But I can't find any Python SocketJS client implementations.. I wonder if the only solution left is to start the websocket server in the Python applicaion (client side) and let the client send it's websocket server details to the Kotlin server, which then will connect to the client's websocket server. It's not a pretty solution, but I wonder if it will work. I'll keep you updated.

Update 1 Feb 2021: I did not spend any more time to this problem. But I will let this post be in case someone figures this out and can help other people with the solution.

解决方案

I was facing the same problem last month. I assume that you are using Stomp over Web Socket for Python. Referring to Websocket Client not receiving any messages, I think you forget to initiate the connection.

Therefore, you should change your python-client code from this

...
 # Connecting to websocket
  ws = websocket.create_connection("ws://localhost:8080/ws")

  # Subscribing to topic
  client_id = str(random.randint(0, 1000))
  sub = stomper.subscribe("/topic/greeting", client_id, ack='auto')
  ws.send(sub)
...

into this

 # Connecting to websocket
 ws = websocket.create_connection("ws://localhost:8080/ws")
  
 # Initate Stomp connection!
 ws.send("CONNECT\naccept-version:1.0,1.1,2.0\n\n\x00\n")

  # Subscribing to topic
  client_id = str(random.randint(0, 1000))
  sub = stomper.subscribe("/topic/greeting", client_id, ack='auto')
  ws.send(sub)

I Hope its worked.

Although, I solve this problem by Implementing the WebSocketApp class from import websocket library, instead of doing procedural steps like your code.

这篇关于Python客户端未从Spring WebSocket服务器接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆