我对套接字的使用还比较陌生,我想让我简单的P5js草图通过套接字与我的Python服务器通信。
我已经学习了一些基础知识,这是到目前为止我能获得的代码:
这是我的python服务器的代码:
#!/usr/bin/env python3 import socket, sys mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mysock.bind( ('127.0.0.1',3000) ) except socket.error: print("Failed to bind") sys.exit() mysock.listen(5) print( "wait for incoming connection") conn, addr = mysock.accept() print( conn ) print( addr ) while True: data = conn.recv(2048) if not data: break print("received data: ") print(data) conn.close() mysock.close()
这是我的sketch.js
文件中的代码:
var socket; function setup() { createCanvas( 720, 400 ); noStroke(); fill(255, 0, 0) frameRate(30); socket = io.connect('http://127.0.0.1:3000'); } function draw() { background(100, 255, 200); } function mouseDragged() { console.log("Sending: " + mouseX + "," + mouseY); var data = { x: mouseX, y: mouseY } socket.emit('mouse', data); }
我正在启动服务器,然后使用http-server
命令提供P5js草图。
当我移至浏览器并在地址http://127.0.0.1:8080
加载网页时,python服务器收到一些消息
wait for incoming connection ('127.0.0.1', 35432) received data: b'GET /socket.io/?EIO=3&transport=polling&t=MK01AKs HTTP/1.1\r\nHost: 127.0.0.1:3000\r\nUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0\r\nAccept: */*\r\nAccept-Language: en-GB,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nReferer: http://127.0.0.1:8080/\r\nOrigin: http://127.0.0.1:8080\r\nCookie: io=7dpapD9jXEGDhpctAAAA; owa_v=cdh%3D%3E83a0a813%7C%7C%7Cvid%3D%3E1517666775149276089%7C%7C%7Cfsts%3D%3E1517666775%7C%7C%7Cdsfs%3D%3E1%7C%7C%7Cnps%3D%3E2; owa_s=cdh%3D%3E83a0a813%7C%7C%7Clast_req%3D%3E1517768497%7C%7C%7Csid%3D%3E1517767571525272799%7C%7C%7Cdsps%3D%3E1%7C%7C%7Creferer%3D%3E%28none%29%7C%7C%7Cmedium%3D%3Edirect%7C%7C%7Csource%3D%3E%28none%29%7C%7C%7Csearch_terms%3D%3E%28none%29\r\nDNT: 1\r\nConnection: keep-alive\r\n\r\n'
即使在浏览器控制台显示很多“ 正在发送:鼠标坐标”消息时,我拖动鼠标也没什么。
我在做什么错了?
提前感谢您的帮助!任何支持将不胜感激。